Why imagecreatefromjpeg not working for .jpg extension? - thumbnails

I have code for thumbnails which works great for gif, png and jpeg files but not for jpg.
Please help me how to make it work for jpg.
I get no errors and nothing in log file.
function create_thumb($src,$dest,$desired_width = false, $desired_height = false){
if (!$desired_height&&!$desired_width) return false;
$fparts = pathinfo($src);
$ext = strtolower($fparts['extension']);
if (!in_array($ext,array('gif','jpg','png','jpeg'))) return false;
if ($ext == 'gif') $resource = imagecreatefromgif($src);
else if ($ext == 'png') $resource = imagecreatefrompng($src);
else if ($ext == 'jpg' || $ext == 'jpeg') $resource = imagecreatefromjpeg($src);
$width = imagesx($resource);
$height = imagesy($resource);
if(!$desired_height) $desired_height = floor($height*($desired_width/$width));
if(!$desired_width) $desired_width = floor($width*($desired_height/$height));
$virtual_image = imagecreatetruecolor($desired_width,$desired_height);
imagecopyresized($virtual_image,$resource,0,0,0,0,$desired_width,$desired_height,$width,$height);
$fparts = pathinfo($dest);
$ext = strtolower($fparts['extension']);
if (!in_array($ext,array('gif','jpg','png','jpeg')))
$ext = 'jpg';$dest = $fparts['dirname'].'/'.$fparts['filename'].'.'.$ext;
if ($ext == 'gif') imagegif($virtual_image,$dest);
else if ($ext == 'png') imagepng($virtual_image,$dest,1);
else if ($ext == 'jpg' || $ext == 'jpeg') imagejpeg($virtual_image,$dest,72);
return array( 'width' => $width, 'height' => $height, 'new_width' => $desired_width, 'new_height'=> $desired_height, 'dest' => $dest ); }

I find solution for me...
$dest = $fparts['dirname'].'/'.$fparts['filename'].'.gif';
imagewebp($virtual_image,$dest,80);
Every image is gif and very small size ;)
Hope it will help to somebody.

Related

PHP preg_replace_callback replace wrong open and end tags

I'm having a problem with my BB-Code function. I've tested followig input to replace:
Testtext! <b>text<u>testtext</u>test</b><b>test</b>
and get this (mixed) output:
Testtext! [b]text[u]testtext[/u]test</b>test<b>test[/b]
my PHP-Code:
function html_to_bbcode($input) {
$regex[] = '#\<b>((?:[^[]|\<(?!/?b>)|(?R))+)\</b>#im';
$regex[] = '#\<i>((?:[^[]|\<(?!/?i>)|(?R))+)\</i>#im';
$regex[] = '#\<u>((?:[^[]|\<(?!/?u>)|(?R))+)\</u>#im';
if (is_array($input)) {
$tag = explode('>', $input[0]);
$tag = str_replace('<', '', $tag[0]);
if ($tag == 'b') {
$input = '[b]'.$input[1].'[/b]';
} else if ($tag == 'i') {
$input = '[i]'.$input[1].'[/i]';
} else if ($tag == 'u') {
$input = '[u]'.$input[1].'[/u]';
}
}
return preg_replace_callback($regex, 'html_to_bbcode', $input);
}
(and some more Tags)
I can't find that bug :( Have anyone an solution for this?

Zend for picture uploads needing to resize images

So, I am using Zend to handle my image uploads. This script works well, but I was wondering if there is a way to resize the image that is being uploaded no matter what the current size is. I've seen 2 similar posts, but their code was entirely different, thus would be difficult to translate into mine from theirs. If possible, I would really like to not have to use extensions, but I will if I have to. Any ideas?
if (isset($_POST['upload'])) {
require_once('scripter/lib.php');
//try {
$destination = 'C:\----';
$uploader = new Zend_File_Transfer_Adapter_Http();
$uploader->setDestination($destination);
$filename = $uploader->getFileName(NULL, FALSE);
$uploader->addValidator('Size', FALSE, '10000kB');
$uploader->addValidator('ImageSize', FALSE, array('minheight' => 100, 'minwidth' => 100));
//$pic = $filename;
if (!$uploader->isValid() || $errors) {
$messages = $uploader->getMessages();
} else {
//$pic = $filename;
$no_spaces = str_replace(' ', '_', $filename, $renamed);
$uploader->addValidator('Extension', FALSE, 'gif, png, jpg');
$recognized = FALSE;
if ($uploader->isValid()) {
$recognized = TRUE;
} else {
$mime = $uploader->getMimeType();
$acceptable = array('jpg' => 'image/jpeg',
'png' => 'image/png',
'gif' => 'image/gif');
$key = array_search($mime, $acceptable);
if (!$key) {
$messages[] = 'Unrecognized image type';
} else {
$no_spaces = "$no_spaces.$key";
$recognized = TRUE;
$renamed = TRUE;
}
}
$uploader->clearValidators();
if ($recognized) {
$existing = scandir($destination);
if (in_array($no_spaces, $existing)) {
$dot = strrpos($no_spaces, '.');
$base = substr($no_spaces, 0, $dot);
$extension = substr($no_spaces, $dot);
$i = 1;
do {
$no_spaces = $base . '_' . $i++ . $extension;
} while (in_array($no_spaces, $existing));
$renamed = TRUE;
}
$uploader->addFilter('Rename', array('target' => $no_spaces));
$success = $uploader->receive();
if (!$success) {
$messages = $uploader->getMessages();
} else {
//$pic = $no_spaces;
$uploaded = "$filename uploaded successfully";
$pic = $filename;
if ($renamed) {
$pic = "imgs/upld/" . $no_spaces;
$uploaded .= " and renamed $no_spaces";
//$pic = $no_spaces;
//$pic = $uploader->getFileName(NULL, FALSE);
} else {$pic = "imgs/upld/" . $filename;;}
$messages[] = "$uploaded";
//$pic = $no_spaces;
}
Zend Framework does not ship with a component for handling images.
Good News! PHP has several components that are really good at dealing with all kinds of image issues.
GD (one of those great PHP extensions) is currently shipped as a core extension for PHP, perhaps you will find it useful.
Maybe this will help: http://phpcodeforbeginner.blogspot.com/2013/04/resize-image-or-crop-image-using-gd.html
(not really trying to be too snarky ;)

Modify code to auto complete on taxonomies instead of title

I've been trying for hours to modify this plugin to work with custom taxonomies instead of post titles and/or post content
http://wordpress.org/extend/plugins/kau-boys-autocompleter/
Added the code / part of the plugin where I think the modification should be done. I could post some stuff I tried but I think it would just confuse people, I don't think I ever came close. Normally I can modify code perfectly but just can't seem to find it. I've tried this method posted here.
http://wordpress.org/support/topic/autocomplete-taxonomy-in-stead-of-title-or-content
But it doesn't work. I've tried searching for possible solutions around his suggestion but I'm starting to think his suggestion isn't even close to fixing it.
if(WP_DEBUG){
error_reporting(E_ALL);
} else {
error_reporting(0);
}
header('Content-Type: text/html; charset=utf-8');
// remove the filter functions from relevanssi
if(function_exists('relevanssi_kill')) remove_filter('posts_where', 'relevanssi_kill');
if(function_exists('relevanssi_query')) remove_filter('the_posts', 'relevanssi_query');
if(function_exists('relevanssi_kill')) remove_filter('post_limits', 'relevanssi_getLimit');
$choices = get_option('kau-boys_autocompleter_choices');
$framework = get_option('kau-boys_autocompleter_framework');
$encoding = get_option('kau-boys_autocompleter_encoding');
$searchfields = get_option('kau-boys_autocompleter_searchfields');
$resultfields = get_option('kau-boys_autocompleter_resultfields');
$titlelength = get_option('kau-boys_autocompleter_titlelength');
$contentlength = get_option('kau-boys_autocompleter_contentlength');
if(empty($choices)) $choices = 10;
if(empty($framework)) $framework = 'jQuery';
if(empty($encoding)) $encoding = 'UTF-8';
if(empty($searchfields)) $searchfields = 'both';
if(empty($resultfields)) $resultfields = 'both';
if(empty($titlelength)) $titlelength = 50;
if(empty($contentlength)) $contentlength = 120;
mb_internal_encoding($encoding);
mb_regex_encoding($encoding);
$words = '%'.$_REQUEST['q'].'%';
switch($searchfields){
case 'post_title' :
$where = 'post_title LIKE "'.$words.'"';
break;
case 'post_content' :
$where = 'post_content LIKE "'.$words.'"';
default :
$where = 'post_title LIKE "'.$words.'" OR post_content LIKE "'.$words.'"';
}
$wp_query = new WP_Query();
$wp_query->query(array(
's' => $_REQUEST['q'],
'showposts' => $choices,
'post_status' => 'publish'
));
$posts = $wp_query->posts;
$results = array();
foreach ($posts as $key => $post){
setup_postdata($post);
$title = strip_tags(html_entity_decode(get_the_title($post->ID), ENT_NOQUOTES, 'UTF-8'));
$content = strip_tags(strip_shortcodes(html_entity_decode(get_the_content($post->ID), ENT_NOQUOTES, 'UTF-8')));
if(mb_strpos(mb_strtolower(($searchfields == 'post_title')? $title : (($searchfields == 'post_content')? $content : $title.$content)), mb_strtolower($_REQUEST['q'])) !== false){
$results[] = array(
'url' => get_permalink($post->ID),
'title' => highlightSearchString(strtruncate($title, $titlelength, true), $_REQUEST['q']),
'content' => (($resultfields == 'both')? highlightSearchString(strtruncate($content, $contentlength, false, '[...]', $_REQUEST['q']), $_REQUEST['q']) : '')
);
}
}
printResults($results, $framework);
function highlightSearchString($value, $searchString){
if((version_compare(phpversion(), '5.0') < 0) && (strtolower(mb_internal_encoding()) == 'utf-8')){
$value = utf8_encode(html_entity_decode(utf8_decode($value)));
}
$regex_chars = '\.+?(){}[]^$';
for ($i=0; $i<mb_strlen($regex_chars); $i++) {
$char = mb_substr($regex_chars, $i, 1);
$searchString = str_replace($char, '\\'.$char, $searchString);
}
$searchString = '(.*)('.$searchString.')(.*)';
return mb_eregi_replace($searchString, '\1<span class="ac_match">\2</span>\3', $value);
}
function strtruncate($str, $length = 50, $cutWord = false, $suffix = '...', $needle = ''){
$str = trim($str);
if((version_compare(phpversion(), '5.0') < 0) && (strtolower(mb_internal_encoding()) == 'utf-8')){
$str = utf8_encode(html_entity_decode(utf8_decode($str)));
}else{
$str = html_entity_decode($str, ENT_NOQUOTES, mb_internal_encoding());
}
if(mb_strlen($str)>$length){
if(!empty($needle) && mb_strpos(mb_strtolower($str), mb_strtolower($needle)) > 0){
$pos = mb_strpos(mb_strtolower($str), mb_strtolower($needle)) + (mb_strlen($needle) / 2);
$startToShort = ($pos - ($length / 2)) < 0;
$endToShort = ($pos + ($length / 2)) > mb_strlen($str);
// build the prefix and suffix
$prefix = $suffix;
if($startToShort){
$prefix = '';
}
if($endToShort){
$suffix = '';
}
// set maximum length
$length = $length - mb_strlen($prefix) - mb_strlen($suffix);
// get the start
if($startToShort){
$start = 0;
} elseif($endToShort){
$start = mb_strlen($str) - $length;
} else {
$start = $pos - ($length / 2);
}
// shorten the string
$string = mb_substr($str, $start, $length);
if($cutWord){
return $prefix.$string.$suffix;
} else {
$firstWhitespace = ($startToShort)? 0 : mb_strpos($string, ' ');
$lastWhitespace =($endToShort)? mb_strlen($string) : mb_strrpos($string, ' ');
return $prefix.' '.(!empty($lastWhitespace)? mb_substr($string, $firstWhitespace, ($lastWhitespace - $firstWhitespace)) : $string).' '.$suffix;
}
} else {
$string = mb_substr($str, 0, $length - mb_strlen($suffix));
return (($cutWord) ? $string : mb_substr($string, 0, mb_strrpos($string, ' ')).' ').$suffix;
}
} else {
return $str;
}
}
function printResults($results, $framework){
if($framework == 'scriptaculous'){
echo '<ul>';
foreach($results as $result){
echo ' <li>
<a href="'.$result['url'].'">
<span class="title">'.$result['title'].'</span>
<span style="display: block;">'.$result['content'].'</span>
</a>
</li>';
}
echo '</ul>';
} else {
foreach($results as $result){
echo str_replace(array("\n", "\r", '|'), array(' ',' ', '|'), '<span class="title">'.$result['title'].'</span><p>'.$result['content'].'</p>')
.'|'
.str_replace(array("\n", "\r", '|'), array(' ',' ', '|'), $result['url'])
."\n";
}
}
}

Uploading transparent images adds a black background

I am trying to make a function to handle avatar uploads.
My problem is, when I upload a transparent image, it turned everything which is transparent black after I resize it.
I have tried using the imagesavealpha() & imagealphablending() options, but the background is still turning black.
It might just be me being blind and not seeing the problem in the code, but I have no idea why it does this.
I can confirm that after the image has been moved to the image/avatars folder just after being uploaded, the background is still transparent.
this is my current code, I have been testing with .png images:
function upload_avatar(){
$base_path = SYSTEM_PATH;
if($_FILES['avatar_img']['tmp_name'] != '') {
$id = md5($this->user_id());
$filename = $_FILES['avatar_img']['name'];
$file_basename = substr($filename, 0, strripos($filename, '.')); // strip extention
$file_ext = substr($filename, strripos($filename, '.')); // strip name
$filesize = $_FILES['avatar_img']['size'];
$newfilename = $id . $file_ext;
if ($file_ext == ".jpg" || $file_ext == ".JPG" || $file_ext == ".jpeg" || $file_ext == ".png" || $file_ext == ".gif"){
if($filesize <= 153600){
move_uploaded_file($_FILES['avatar_img']['tmp_name'], $base_path."/images/avatars/" . $newfilename);
//resize image form
list($width, $height) = getimagesize($base_path."/images/avatars/" . $newfilename);
$scale_height = $height/$width;
$scale_width = $width/$height;
//Find height and width of the image
if($width > $height && $width > 150){
$width_new = 150;
$height_new = round($width_new*$scale_height);
}else if($height > $width && $height > 150){
$height_new = 150;
$width_new = round($height_new*$scale_width);
}else{
$height_new = $height;
$width_new = $width;
}
switch($file_ext) {
case ".jpg" :
case ".jpeg":
$source = imagecreatefromjpeg($base_path."/images/avatars/" . $newfilename);
break;
case ".png" :
$source = imagecreatefrompng($base_path."/images/avatars/" . $newfilename);
break;
default:
$source = imagecreatefromgif($base_path."/images/avatars/" . $newfilename);
break;
}
$destination = imagecreatetruecolor($width_new, $height_new);
imagesavealpha($destination, true);
imagealphablending($destination, true);
imagecopyresized($destination, $source, 0, 0, 0, 0, $width_new, $height_new, $width, $height);
switch($file_ext) {
case ".jpg":
case ".jpeg":
imagejpeg($destination, $base_path."/images/avatars/" . $newfilename, 85);
break;
case ".png":
imagepng($destination, $base_path."/images/avatars/" . $newfilename, 8);
break;
default:
imagegif($destination, $base_path."/images/avatars/" . $newfilename, 85);
break;
}
return $newfilename;
}else{
$this->upload_avatar = '<br />But the avatar was not updated. The avatar\'s size exceeded the 150kb limit. ';
return '';
}
}else{
$this->upload_avatar = '<br />But the avatar was not updated. The avatar must be one of the following formats: jpg, jpeg, png or gif. ';
return '';
}
}else{
return '';
}
}
Any help would be appreciated as I am going nuts looking at this now.
Thanks!
This here may be what you're looking for. The second comment contains an example of resizing pngs and gifs while preserving transparency.
p.s. I'd have added this as a comment but I don't have the rights to do that yet.

Zend Framework - how to upload a file

How can i upload a file? Stackoverflow i cant page codes so please check this link: http://pastebin.org/386639
Thanks in advance
LATER:
Later i updated this as following, because ZF is not friendly, they keep still everything top secret! :P
public static function mvUploadFile()
{
//
// $_GET/_POST/FILE what ever
//
$fname = basename( $_FILES['attachment']['name']);
$_fname = strtolower (end(explode('.',$fname) ) );
Zend_Debug::dump( $_FILES );
//
// Filter the file
//
switch($_fname)
{
case ($_fname == 'jpg' ||
$_fname == 'jpeg' ||
$_fname == 'gif' ||
$_fname == 'bmp' ||
$_fname == 'png' ||
$_fname == 'html' ||
$_fname == 'pdf' ||
$_fname == 'doc' ||
$_fname == 'docx' ||
$_fname == 'xls'
):
$target_path = APPLICATION_PATH . "/../public/files/textual_translation_attachment/";
//chmod("../up" , 0777);
$target_path = $target_path . basename( $_FILES['attachment']['name']);
if(move_uploaded_file($_FILES['attachment']['tmp_name'], $target_path)) {
//echo "The file ". basename( $_FILES['file']['name']). " has been uploaded";
//$_sql = "insert into a (huis,image) values ('$_app','$_file')";
// send the file name only .....
//echo $fname ;
}else{
//echo "error ";
}
break;
}
return $fname;
}
If you
Zend_Debug::dump($_FILES);
Do you see your file?
If you are using jQuery, you may want to try Uploadify. This can be done using the
Zend Framework Uploadify Extension
http://gondo.webdesigners.sk/zend-framework-uploadify-extension/