Png black background when upload and resize image - php

Can you help me with my code in php?
I don't know how make my pictures transparent. They have black background after the uploading. I have the code here. (and some text for small post and content)
Thhank you.
<?php
function zmensi_obrazok($image_max_width, $image_max_height, $obrazok, $obrazok_tmp, $obrazok_size, $filename){
$postvars = array(
"image" => $obrazok,
"image_tmp" => $obrazok_tmp,
"image_size" => $obrazok_size,
"image_max_width" => $image_max_width,
"image_max_height" => $image_max_height
);
$valid_exts = array("jpg","jpeg","png");
$ext = end(explode(".",strtolower($obrazok)));
if($postvars["image_size"] <= 1024000){
if(in_array($ext,$valid_exts)){
if($ext == "jpg" || $ext == "jpeg"){
$image = imagecreatefromjpeg($postvars["image_tmp"]);
}
else if($ext == "png"){
$image = imagecreatefrompng($postvars["image_tmp"]);
}
list($width,$height) = getimagesize($postvars["image_tmp"]);
$old_width = imagesx($image);
$old_height = imagesy($image);
$scale = min($postvars["image_max_width"]/$old_width, $postvars["image_max_height"]/$old_height);
$new_width = ceil($scale*$old_width);
$new_height = ceil($scale*$old_height);
$tmp = imagecreatetruecolor($new_width,$new_height);
imagecopyresampled($tmp,$image,0,0,0,0,$new_width,$new_height,$width,$height);
imagejpeg($tmp,$filename,100);
return "";
imagedestroy($image);
imagedestroy($tmp);
}
}
}
?>

I think this link will answer your question:
http://www.php.net/manual/pl/function.imagecopyresampled.php#104028
In your code the answer will be something like:
// preserve transparency
if($ext == "gif" or $ext == "png"){
imagecolortransparent($tmp, imagecolorallocatealpha($tmp, 0, 0, 0, 127));
imagealphablending($tmp, false);
imagesavealpha($tmp, true);
}
Paste this before executing imagecopyresampled.

If you did want to save to a JPEG rather than saving to a PNG, you can just change the background colour of the target image to white before you do the copy:
$tmp = imagecreatetruecolor($new_width,$new_height);
imagefilledrectangle($tmp, 0, 0, $new_width, $new_height, imagecolorallocate($tmp, 255, 255, 255));
imagecopyresampled($tmp,$image,0,0,0,0,$new_width,$new_height,$width,$height);
Then you'll end up with a JPEG without any transparency, but the background colour will be white rather than black.

Related

In PHP, how do you add whitespace around a non-square photo, so that it is always 200x200 pixels?

This script below works fine to handle an uploaded image and resize it so that the max height or width (whichever side is longer) is 200px. So it could be 200x200 if it's perfect square image, or 200x140, or 140x200, etc.
if(isset($_FILES['image'])) {
$img = $_FILES['image']['name'];
$tmp = $_FILES['image']['tmp_name'];
// get uploaded file's extension
$ext = strtolower(pathinfo($img, PATHINFO_EXTENSION));
//checking if image exists for this pool and removing if so, before adding new image in its place
if(file_exists("uploads/".$poolid.".png")) {
unlink("uploads/".$poolid.".png");
}
// checks valid format
if(in_array($ext, $valid_extensions)) {
//re-size the image and make it a PNG before sending to server
$final_image = $poolid . ".png";
$path = "uploads/".strtolower($final_image);
$size = getimagesize($tmp);
$ratio = $size[0]/$size[1]; // width/height
if( $ratio > 1) {
$width = 200;
$height = 200/$ratio;
}
else {
$width = 200*$ratio;
$height = 200;
}
$src = imagecreatefromstring(file_get_contents($tmp));
$dst = imagecreatetruecolor($width,$height);
imagecopyresampled($dst,$src,0,0,0,0,$width,$height,$size[0],$size[1]);
imagedestroy($src);
imagepng($dst, $path); // adjust format as needed
imagedestroy($dst);
$_SESSION['image_uploaded']="yes";
echo $path ."?".rand(1,32000);
} else {
echo 'invalid file';
}
}
Now, Facebook sharing using OpenGraph requires an image to be at least 200x200. So a 140x200 image wouldn't work with their sharing functionality.
I don't love non-square images anyway, so I would like to take the image and if it's not already a square, I'd like to add whitespace to the sides (or on the top/bottom) and save it as a perfect 200x200 square every single time.
I tried this below, but it's not working (no image gets created at all). What is wrong with what I tried to do? This doesn't seem overly complicated but clearly I'm missing something.
if(isset($_FILES['image'])) {
$img = $_FILES['image']['name'];
$tmp = $_FILES['image']['tmp_name'];
// get uploaded file's extension
$ext = strtolower(pathinfo($img, PATHINFO_EXTENSION));
//checking if image exists for this pool and removing if so, before adding new image in its place
if(file_exists("uploads/".$poolid.".png")) {
unlink("uploads/".$poolid.".png");
}
// checks valid format
if(in_array($ext, $valid_extensions)) {
//re-size the image and make it a PNG before sending to server
$final_image = $poolid . ".png";
$path = "uploads/".strtolower($final_image);
$size = getimagesize($tmp);
$ratio = $size[0]/$size[1]; // width/height
if( $ratio > 1) {
$width = 200;
$height = 200/$ratio;
}
else {
$width = 200*$ratio;
$height = 200;
}
$src = imagecreatefromstring(file_get_contents($tmp));
$dst = imagecreatetruecolor($width,$height);
$orig_img=imagecopyresampled($dst,$src,0,0,0,0,$width,$height,$size[0],$size[1]);
imagedestroy($src);
// create new image and fill with background colour
$new_img = imagecreatetruecolor($output_w, $output_h);
$bgcolor = imagecolorallocate($new_img, 255, 0, 0); // red
imagefill($new_img, 0, 0, $bgcolor); // fill background colour
// copy and resize original image into center of new image
$final_img=imagecopyresampled($new_img, $orig_img, 0, 0, 0, 0, 200, 200, $width, $height);
imagepng($final_img, $path); // adjust format as needed
imagedestroy($dst);
$_SESSION['image_uploaded']="yes";
echo $path ."?".rand(1,32000);
} else {
echo 'invalid file';
}
}
You don't need a temporary intermediate image. You can paste the resampled source image right into the destination image after you fill it with background. See here:
$src = imagecreatefromstring(file_get_contents($tmp));
// Create new image and fill it with background color
$dst = imagecreatetruecolor($output_w,$output_h);
$bgcolor = imagecolorallocate($dst, 255, 0, 0);
imagefill($dst, 0, 0, $bgcolor);
// Copy resampled src image into dst
if ($ratio > 1)
imagecopyresampled($dst, $src, 0, ($output_h - $height) / 2, 0, 0, $width, $height, $size[0], $size[1]);
else
imagecopyresampled($dst, $src, ($output_w - $width) / 2, 0, 0, 0, $width, $height, $size[0], $size[1]);
imagepng($dst, $path); // adjust format as needed
imagedestroy($src);
imagedestroy($dst);

Data Loss in JPEG/PNG resizing

I've adapted this code that I found. It resizes .jpg and .png images, and maintains alpha layers.
When I resize an image, however, the reduction in file size is far more than I had anticipated. This isn't a problem for me, as I cannot see with my eyes any degradation or data loss.
What is causing the huge compression of the file, and if I ever needed to, how can I avoid it?
function thumbnail($image, $width, $height, $target) {
if($image[0] != "/") { // Decide where to look for the image if a full path is not given
if(!isset($_SERVER["HTTP_REFERER"])) { // Try to find image if accessed directly from this script in a browser
$image = $_SERVER["DOCUMENT_ROOT"].implode("/", (explode('/', $_SERVER["PHP_SELF"], -1)))."/".$image;
} else {
$image = implode("/", (explode('/', $_SERVER["HTTP_REFERER"], -1)))."/".$image;
}
} else {
$image = $_SERVER["DOCUMENT_ROOT"].$image;
}
$image_properties = getimagesize($image);
$image_width = $image_properties[0];
$image_height = $image_properties[1];
$image_ratio = $image_width / $image_height;
$type = $image_properties["mime"];
if(!$width && !$height) {
$width = $image_width;
$height = $image_height;
}
if(!$width) {
$width = round($height * $image_ratio);
}
if(!$height) {
$height = round($width / $image_ratio);
}
if($type == "image/jpeg") {
header('Content-type: image/jpeg');
$thumb = imagecreatefromjpeg($image);
} elseif($type == "image/png") {
header('Content-type: image/png');
$thumb = imagecreatefrompng($image);
} else {
return false;
}
$temp_image = imagecreatetruecolor($width, $height);
imagealphablending($temp_image, false);
imagesavealpha($temp_image,true);
$transparent = imagecolorallocatealpha($temp_image, 255, 255, 255, 127);
imagefilledrectangle($temp_image, 0, 0, $nWidth, $nHeight, $transparent);
imagecopyresampled($temp_image, $thumb, 0, 0, 0, 0, $width, $height, $image_width, $image_height);
//$thumbnail = imagecreatetruecolor($width, $height);
//imagecopyresampled($thumbnail, $temp_image, 0, 0, 0, 0, $width, $height, $width, $height);
if($type == "image/jpeg") {
imagejpeg($temp_image, 'img/'.$target.'.jpg');
} else {
imagepng($temp_image,'img/'.$target.'.png');
}
imagedestroy($temp_image);
//imagedestroy($thumbnail);
}
As showdev commented, both imagejpeg() and imagepng() accept a third optional parameter for the image quality. For imagejpeg() it runs from 0 to 100 and defaults to 75), for imagepng() it is from 0 to 9 and defaults to 6.
Also, 4.4Mb is a really big size for a ~2.4Mpx image. It problably contains a lot of metadata and most of it -like Photoshop thumbsnails- is not preserved when you do an imagecopyresampled() with PHP's GD library.
You should also run one of your test images through a lossless compression program like JStrip (http://davidcrowell.com/jstrip/), to check how much it weights without the bloat.

Php Resizing image increase image size

I'm creating thumnails of uploaded file.
if image width and height are greater than 200 than then i re size them to 200px.
Here is code i used to do that:
if (file_exists($old_file)) {
$path_parts = pathinfo($old_file);
$extension = $path_parts['extension'];
$filename_path = $filepath . $filename;
$destination_path = $filename_path;
if (strtolower($extension) == "jpg" || strtolower($extension) == "jpeg") {
$uploadedfile = $old_file;
$src = imagecreatefromjpeg($uploadedfile);
} else if (strtolower($extension) == "png") {
$uploadedfile = $old_file;
$src = imagecreatefrompng($uploadedfile);
} else {
$uploadedfile = $old_file;
$src = imagecreatefromgif($uploadedfile);
}
list($width, $height) = getimagesize($uploadedfile);
$newwidth = $Size['width'];
$newheight = $Size['height'];
if ($width <= $newwidth && $height <= $newheight) {
$newwidth = $width;
$newheight = $height;
$tmp = imagecreatetruecolor($width, $height);
} else {
if ($width > $height) {
$newheight = ($height / $width) * $newwidth;
$tmp = imagecreatetruecolor($newwidth, $newheight);
} else {
$newwidth = ($width / $height) * $newheight;
$tmp = imagecreatetruecolor($newwidth, $newheight);
}
}
if ((strtolower($extension) == "png") OR (strtolower($extension) == "gif")) {
imagealphablending($tmp, false);
imagesavealpha($tmp, true);
$transparent = imagecolorallocatealpha($tmp, 255, 255, 255, 127);
imagefilledrectangle($tmp, 0, 0, $newwidth, $newheight, $transparent);
}
imagecopyresampled($tmp, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
if (strtolower($extension) == "jpg" || strtolower($extension) == "jpeg") {
imagejpeg($tmp, $destination_path, 100);
} elseif (strtolower($extension) == "png") {
imagepng($tmp, $destination_path, 5);
} else {
imagegif($tmp, $destination_path);
}
chmod($destination_path, 0777);
imagedestroy($src);
imagedestroy($tmp);
ob_flush();
flush();
ob_end_flush();
return true;
} else {
return false;
}
it re size the large images to 200px by 200px but image size is increased in (byte and kb etc increased).
I tried uploading 8kb png file, and new thumbnail file size was 28kb?
Tried googling but didn't find anything helpful
Thanks.
Your source image is compressed, after parsing it you get a true color image, which is uncompressed. Then you save it with a compression level of 5 (in the case of PNG), which is pretty low compression, thus a higher filesize.
Try a higher compression, like 9, for example. Also try adding a combination of filters to decrease filesize (http://us3.php.net/manual/en/image.constants.php look for PNG_FILTER_*).
See: http://us3.php.net/manual/en/function.imagepng.php
http://en.wikipedia.org/wiki/Portable_Network_Graphics#Compression
http://en.wikipedia.org/wiki/Portable_Network_Graphics#File_size_factors
The GD library doesn't appear to provide any interfaces to let you in on low-level PNG data, but you can theoretically find out the source compression level and filters, by using other bindings or trying to read it manually.
http://www.libpng.org/pub/png/spec/1.2/PNG-Compression.html
http://www.libpng.org/pub/png/spec/1.2/PNG-Filters.html
The same may happen with JPG and GIF.

Codeigniter Image Library Cropping an Image with 2 sets of coordinates to make square anywhere?

Spending time reading through the docs, and searching for examples. I understand cropping an image from top 0, and left 0 is pretty straight forward. However. I would like to pass 2 sets of coordinates, a starting point and an ending point. Four Points, a Square that is defined anywhere. However from the examples I am finding, and from what I gather the rendition is not going to let me do this. codeigniter so I am seeking confirmation on this thought, is it true that I can only provide end points from 0, and it crops a square based on said end points or can I actually specify an x start, an x end, and similar for y?
Or is there some other technique I can use within codeigniter that will allow me to pass for coordinates for starting and ending points?
You can use for example of class of defined cropping image and call it a class via library or helper in a codeigniter:
For example call it:
LibraryCropImage::ResizedThumbnail($profile_thumbsize_x, $profile_thumbsize_x, $path, $filename, $path_to, $filename_to.'_sized', $quality, $fileextension);
LibraryCropImage::CroppedThumbnail($profile_thumbsize_x, $profile_thumbsize_x, $path, $filename, $path_to, $filename_to.'_cropped', $quality, $fileextension);
abstract class LibraryCropImage {
function ResizedThumbnail($thumbnail_width, $thumbnail_height, $path, $filename, $path_to, $filename_to, $quality, $ext)
{
list($width, $height) = getimagesize($path.$filename);
$new_width = $thumbnail_width;
$new_height = $thumbnail_height;
if ($ext == "jpg" || $ext == "jpeg")
{
$thumb = #imagecreatefromjpeg($path.$filename);
}
else if ($ext == "gif")
{
$thumb = #imagecreatefromgif($path.$filename);
}
else if ($ext == "png")
{
$thumb = #imagecreatefrompng($path.$filename);
}
$thumbp = imagecreatetruecolor($new_width, $new_height);
imagecopyresampled($thumbp, $thumb, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
ob_start();
if ($ext == "jpg" || $ext == "jpeg")
{
imagejpeg($thumbp, null, $quality);
}
else if ($ext == "gif")
{
imagegif($thumbp);
}
else if ($ext == "png")
{
imagepng($thumbp, null);
}
$i = ob_get_clean();
$fp = fopen($path_to.$filename_to.'.'.$ext, 'w');
fwrite ($fp, $i);
fclose ($fp);
imagedestroy($thumbp);
}
function CroppedThumbnail($thumbnail_width, $thumbnail_height, $path, $filename, $path_to, $filename_to, $quality, $ext)
{
list($width, $height) = getimagesize($path.$filename);
$new_width = $thumbnail_width;
$new_height = $thumbnail_height;
if ($ext == "jpg" || $ext == "jpeg")
{
$image = #imagecreatefromjpeg($path.$filename);
}
else if ($ext == "gif")
{
$image = #imagecreatefromgif($path.$filename);
}
else if ($ext == "png")
{
$image = #imagecreatefrompng($path.$filename);
}
$filename = $path.$filename;
$thumb_width = $thumbnail_width;
$thumb_height = $thumbnail_height;
$width = imagesx($image);
$height = imagesy($image);
$original_aspect = $width / $height;
$thumb_aspect = $thumb_width / $thumb_height;
if($original_aspect >= $thumb_aspect) {
// If image is wider than thumbnail (in aspect ratio sense)
$new_height = $thumb_height;
$new_width = $width / ($height / $thumb_height);
} else {
// If the thumbnail is wider than the image
$new_width = $thumb_width;
$new_height = $height / ($width / $thumb_width);
}
$thumb = imagecreatetruecolor($thumb_width, $thumb_height);
// Resize and crop
imagecopyresampled($thumb,
$image,
0 - ($new_width - $thumb_width) / 2, // Center the image horizontally
0 - ($new_height - $thumb_height) / 2, // Center the image vertically
0, 0,
$new_width, $new_height,
$width, $height);
ob_start();
if ($ext == "jpg" || $ext == "jpeg")
{
imagejpeg($thumb, null, $quality);
}
else if ($ext == "gif")
{
imagegif($thumb);
}
else if ($ext == "png")
{
imagepng($thumb, null);
}
$i = ob_get_clean();
$fp = fopen($path_to.$filename_to.'.'.$ext, 'w');
fwrite ($fp, $i);
fclose ($fp);
imagedestroy($thumb);
}
}
Suggestions for you:
Use imagecopyresized()
Use exec() in conjunction with vcrop on Debian
Use Imagick::cropImage or exec() in conjunction with convert -crop
I answered this question here: how to crop image in codeigniter?
Basically, you provide two axes (x/y). But it will not crop the area from 0 to that axis as you think, it will actually return the part which is closer to the center. So for that reason it is possible to crop out an area between (x1,y1) and (x2,y2).

help needed to resize an image in php

I have a bit of code that generates thumbnails from an uploaded image. The only problem is that it cuts portrait images off, rather than resizing the portrait image to fit the height of the thumbnail, landscape images are fine. I was wondering if anyone could help me out to change the code so it will place portrait images inside the thumbnail properly? (if that makes sense?)
Here's the code:
$setSize = 150;
$setHSize = 113;
$jpeg_quality = 75;
list($width, $height, $type, $attr) = getimagesize($origPath);
$newW = $setSize;
$newH = round( $height * ( $setSize / $width ) );
$img_r = imagecreatefromjpeg($origPath) or notfound();
$dst_r = ImageCreateTrueColor( $setSize, $setHSize );
$heightOffset = round( ($setHSize-$newH)/2 );
$white = imagecolorallocate($dst_r, 255, 255, 255);
imagefilledrectangle($dst_r, 0, 0, $setSize, $setHSize, $white);
imagecopyresampled($dst_r, $img_r, 0, $heightOffset, 0, 0, $newW, $newH, $width, $height);
header("Content-type: image/jpeg");
imagejpeg($dst_r, $thbPath, $jpeg_quality);
I just don't fully understand the way php creates images, so any help would be appreciated :)
The way you compute $newW and $newH is incorrect for what you want. You are giving preference to the width, so most landscape images will look okay, but portrait will be cut off. Try the following instead:
// assume landscape and see how things look
$newW = $setSize;
$newH = round( $height * ( $setSize / $width ) );
if ($newH > $setHSize) {
// portrait image
$newH = $setHSize;
$newW = round( $width * ( $setHSize / $height ) );
}
I hope this helps!
Hope this helps.
<?php
define('DOCROOT', $_SERVER['DOCUMENT_ROOT']);
include_once(DOCROOT."/dbc.php");
//**********************| Resize based on height
$photo_height = 350;
//**********************| Get the file from the post
$file = $_FILES['file'];
$path_thumbs = (DOCROOT."/gallery/");
$path_big = (DOCROOT."/trash/");
//**********************| Check permission
if (!is_writeable($path_thumbs)){
die ("Error: The directory <b>($path_thumbs)</b> is NOT writable");
}
if (!is_writeable($path_big)){
die ("Error: The directory <b>($path_big)</b> is NOT writable");
}
//**********************| Make sure you have a file
if (isset($file)){
$file_type = $_FILES['file']['type'];
$file_name = $_FILES['file']['name'];
$file_size = $_FILES['file']['size'];
$file_tmp = $_FILES['file']['tmp_name'];
$getExt = explode ('.', $file_name);
$file_ext = $getExt[count($getExt)-1];
//**********************| Make new name
$rand_name = md5(time());
$rand_name= rand(0,999999999);
//**********************| See the kind of file we have
if($file_size){
if($file_type == "image/pjpeg" || $file_type == "image/jpeg"){
$new_img = imagecreatefromjpeg($file_tmp);
}
elseif($file_type == "image/x-png" || $file_type == "image/png"){
$new_img = imagecreatefrompng($file_tmp);
}
elseif($file_type == "image/gif"){
$new_img = imagecreatefromgif($file_tmp);
}
//**********************| Get the height and width
list($width, $height) = getimagesize($file_tmp);
$imgratio=$height/$width;
if ($photo_height >= $height){
//*********** Dont resize if the image is smaller then $photo_height = 350;
$newwidth = $width;
$newheight = $height;
}
elseif ($imgratio>1){
$newheight = $photo_height;
$newwidth = $photo_height/$imgratio;
}
else{
$newwidth = $photo_height;
$newheight = $photo_height*$imgratio;
}
if (function_exists(imagecreatetruecolor)){ $resized_img = imagecreatetruecolor($newwidth,$newheight); }
else{ die("Error: Please make sure you have GD library ver 2+");
}
imagecopyresampled($resized_img, $new_img, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
ImageJpeg ($resized_img,"$path_thumbs/$rand_name.$file_ext",'100');
ImageDestroy ($resized_img);
ImageDestroy ($new_img);
}
move_uploaded_file ($file_tmp, "$path_big/$rand_name.$file_ext");
$newimage = "$rand_name.$file_ext";
}
else {
echo "Sorry, there was a problem, Please try again.\n\n";
}
adaptiveResizeImage
or
adaptiveCropThumblanil
in Imagick can help you

Categories