Black result image problem on BMP image resize using PHP - php

I have a PHP script to re size image file as below;
$file = "test.bmp";
$ext = pathinfo($file, PATHINFO_EXTENSION);
$info = pathinfo($file);
$file_name = basename($file,'.'.$info['extension']);
$thumbname = "thumb/".$file_name.".".$ext;
$maxh = 200;
$maxw = 200;
$quality = 100;
list($width,$height)=getimagesize($file);
$src = imagecreatefromwbmp($file);
$tmp = imagecreatetruecolor($maxw,$maxh);
imagecopyresampled($tmp,$src,0,0,0,0,200,200,$width,$height);
imagejpeg($tmp,$thumbname,$quality);
imagedestroy($tmp);
The script is suppose to resize a Windows bitmap image to 200x200 thumbnail. But instead, I am getting a black 200x200 image. I am using PHP with Apache in Windows PC. How can I fix this?

.bmp and wbmp are VERY, VERY different file types.
Note the content-type headers:
Content-Type: image/x-xbitmap
Content-Type: image/vnd.wap.wbmp
Calling imagecreatefromwbmp($file) where $file is a .bmp will fail every time.
See this thread for info on how to load a .bmp file. It's not pretty.

As pointed out in PHP imagecopyresampled() docs:
Note:
There is a problem due to palette image limitations (255+1 colors). Resampling or filtering an image commonly needs more colors than 255, a kind of approximation is used to calculate the new resampled pixel and its color. With a palette image we try to allocate a new color, if that failed, we choose the closest (in theory) computed color. This is not always the closest visual color. That may produce a weird result, like blank (or visually blank) images. To skip this problem, please use a truecolor image as a destination image, such as one created by imagecreatetruecolor().
To see if it's the case you can use imageistruecolor() and copy the contents to a new truecolor image before "copyresampling" it:
if( !imageistruecolor($src) ){
$newim = imagecreatetruecolor( $width, $height );
imagecopy( $newim, $src, 0, 0, 0, 0, $width, $height );
imagedestroy($src);
$src = $newim;
}

There is a new opensource project on Github that allows reading and saving of BMP files (and other file formats) in PHP.
The project is called PHP Image Magician.

<?php
//Create New 'Thumbnail' Image
$newImageWidth = 200;
$newImageHeight = 200;
$newImage = imagecreatetruecolor($newImageWidth, $newImageHeight);
$newImageFile = 'output.jpg';
$newImageQuality = 100;
//Load old Image(bmp, jpg, gif, png, etc)
$oldImageFile = "test.jpg";
//Specific function
$oldImage = imagecreatefromjpeg($oldImageFile);
//Non-Specific function
//$oldImageContent = file_get_contents($oldImageFile);
//$oldImage = imagecreatefromstring($oldImageContent);
//Get old Image's details
$oldImageWidth = imagesx($oldImage);
$oldImageHeight = imagesy($oldImage);
//Copy to new Image
imagecopyresampled($newImage, $oldImage, 0, 0, 0, 0, $newImageWidth, $newImageHeight, $oldImageWidth, $oldImageHeight);
//Output to file
imagejpeg($newImage, $newImageFile, $newImageQuality);

Related

How to compress / reduce quality of base64 image with php?

I have stored multiple images in base64 inside my database. I get images using php as image path. But I want to reduce size of my image when decoding it from base64, because it slows down my app if I load full size image. (Full size image I need just in backend).
/*
DB stuff getting base64 string from database
$img = base64 string (can be with 'data:image/jpg;base64,' in front, thats for the str_replace())
*/
if($img){
header("Content-Type: image/png");
echo base64_decode(str_replace("data:image/jpg;base64,","",$img));
}
Everything works nice this way. I use it like this:
<img src="http://example.com/getimg.php?id=4" />
or in css. I need this because of security reasons, I cant store any image on server, also in path I have access_token variable, so random person cant see images.
Is there a way to do this without storing the actual image in server?
You can use imagecreatefromstring and imagecopyresized.
Live example here
<?php
if ($img) {
$percent = 0.5;
// Content type
header('Content-Type: image/jpeg');
$data = base64_decode($img);
$im = imagecreatefromstring($data);
$width = imagesx($im);
$height = imagesy($im);
$newwidth = $width * $percent;
$newheight = $height * $percent;
$thumb = imagecreatetruecolor($newwidth, $newheight);
// Resize
imagecopyresized($thumb, $im, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
// Output
imagejpeg($thumb);
}

CSS - Transparent bg of image not rendering on website

I'm trying to redesign my site so that my original square, tile-based rendering of images can be more of a cutout of the image... to get rid of that grid pattern.
Here's how it looked originally...
Here's a rough mock-up of what I'm going for:
So I resaved an image thumbnail with a transparent background... I just want the dog to show, and the square is transparent which will show the site's background underneath.
Yet when I render it on the page, it has this black background.
I've checked my CSS to see if there is some sort of img class, or class for the rendered comics... or even the bootstrap to see where there may be a background-color being assigned to black (and also searched for hex code 000000), but didn't find one...
Do you know why this may be happening?
Thanks!
EDIT: I've just noticed something...
My logo at the top renders with a transparent background... and the element is a png file... therefore, its MIME type is image/png.
I'm using a thumbnailing script to make the thumbnails smaller, but now the element is of thumber.php, which puts it as MIME type image/jpeg.
So I guess it's my thumbnailing script that changing the MIME type.
So I checked it, and it's creating the file as a jpeg
//imagejpeg outputs the image
imagejpeg($img);
Is there a way to change it so that the resampled image is output as a png?
Thumbnailing script:
<?php
#Appreciation goes to digifuzz (http://www.digifuzz.net) for help on this
$image_file = $_GET['img']; //takes in full path of image
$MAX_WIDTH = $_GET['mw'];
$MAX_HEIGHT = $_GET['mh'];
global $img;
//Check for image
if(!$image_file || $image_file == "") {
die("NO FILE.");
}
//If no max width, set one
if(!$MAX_WIDTH || $MAX_WIDTH == "") {
$MAX_WIDTH="100";
}
//if no max height, set one
if(!$MAX_HEIGHT || $MAX_HEIGHT == "") {
$MAX_HEIGHT = "100";
}
$img = null;
//create image file from 'img' parameter string
$img = imagecreatefrompng($image_file);
//if image successfully loaded...
if($img) {
//get image size and scale ratio
$width = imagesx($img);
$height = imagesy($img);
//takes min value of these two
$scale = min($MAX_WIDTH/$width, $MAX_HEIGHT/$height);
//if desired new image size is less than original, output new image
if($scale < 1) {
$new_width = floor($scale * $width);
$new_height = floor($scale * $height);
$tmp_img = imagecreatetruecolor($new_width, $new_height);
//copy and resize old image to new image
imagecopyresampled($tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
imagedestroy($img);
//replace actual image with new image
$img = $tmp_img;
}
}
//set the content type header
header("Content-type: image/png");
//imagejpeg outputs the image
imagealphablending($img, false);
imagesavealpha($img, true);
imagepng($img);
imagedestroy($img);
?>
You will need to make some changes in the image generator and see if that works out for you.
The crucial changes are within the setting of the header and the method of image generation. You will be looking for these following two
header('Content-Type: image/jpeg');
change to:
header('Content-Type: image/png');
imagejpeg($im);
change to:
imagepng($im)
When dealing with png images with an alpha channel you should take a few extra steps.
Before spitting it out with imagepng(), these lines will need to be added.
imagealphablending($img, false);
imagesavealpha($img, true);
This information can be found on php.net
Edit:
Try with these alterations to this code:
if($scale < 1) {
$new_width = floor($scale * $width);
$new_height = floor($scale * $height);
$tmp_img = imagecreatetruecolor($new_width, $new_height);
imagealphablending($tmp_img,true); // add this line
//copy and resize old image to new image
imagecopyresampled($tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
$img = $tmp_img;
// remove line here
}
}
header("Content-type: image/png");
imagesavealpha($img, true);
imagepng($img);
imagedestroy($img);
imagedestroy($tmp_img); // add this line here
Basically you create new layers and put these together. For each layer you will need to set the alpha blending. I was successful in creating alpha images. Let me know what your findings are .. :-) ..

Photo color loss after watermarking

Having a few teething problems watermarking a photo. It all works fine apart from the watermarked photo's colors become duller than they should be - very noticeable in-fact.
I'm using imagecopyresized to do my watermarking, as this specifically allows me to use PNG-24 watermarks, the others do not. I know the colors are usually OK, as I have just used readfile($url) as a test, and the photos are perfect.
Here is my script:
<?php
// get parent and watermark images & sizes
$image = imagecreatefromjpeg($url);
$imageSize = getimagesize($url);
$watermark = imagecreatefrompng('watermark.png');
$watermark_o_width = imagesx($watermark);
$watermark_o_height = imagesy($watermark);
// calculate new watermark width and position
if ($imageSize[0] > $imageSize[1] || $imageSize[0] == $imageSize[1]) {
$leftPercent = 23;
} else {
$leftPercent = 7;
}
$leftPixels = ($imageSize[0]/100)*$leftPercent;
$newWatermarkWidth = $imageSize[0]-$leftPixels;
$newWatermarkHeight = $watermark_o_height * ($newWatermarkWidth / $watermark_o_width);
// place watermark on parent image, centered and scaled
imagecopyresized(
$image,
$watermark,
$imageSize[0]/2 - $newWatermarkWidth/2,
$imageSize[1]/2 - $newWatermarkHeight/2,
0,
0,
$newWatermarkWidth,
$newWatermarkHeight,
imagesx($watermark),
imagesy($watermark)
);
// print
imagejpeg($image);
// destroy
imagedestroy($image);
imagedestroy($watermark);
?>
How can I stop this from happening? I'm reading about imagecreatetruecolor, does that solve the issue? I'm Googling "imagecreatetruecolor color loss photos" and variations but nobody really talks about this issue. If I do need this function, where would I add that to this script?
This has totally thrown a spanner in the works for me and would love for somebody to tell me where to stick it (not literally).
Here is an example of the color loss. The preview image should be exactly the same colors as the thumbnail. The thumbnails are created using readfile() whereas the previews are created using imagecreatefromjpeg and imagecopresized.
This example code works fine, by using the same characteristics as your images:
Original JPG: dark background; beautiful girl; red dress.
Watermark PNG: transparent background; text; gray color.
<?php
// Path the the requested file (clean up the value if needed)
$path = $url;
// Load image
$image = imagecreatefromjpeg($path);
$w = imagesx($image);
$h = imagesy($image);
// Load watermark
$watermark = imagecreatefrompng('watermark.png');
$ww = imagesx($watermark);
$wh = imagesy($watermark);
// Merge watermark upon the original image (center center)
imagecopy($image, $watermark, (($w/2)-($ww/2)), (($h/2)-($wh/2)), 0, 0, $ww, $wh);
// Output the image to the browser
header('Content-type: image/jpeg');
imagejpeg($image);
// destroy both images
imagedestroy($image);
imagedestroy($watermark);
// kill script
exit();
?>
Left: Output Image | Right: Original Image
Note:
The output image was compressed several times until: Original -> PHP Output -> GIMP -> Here.
After much testing, I came to the conclusion that PHP's GD Image does not support color profiles on the images that are being watermarked. I am now using Imagick and the colors are perfect.

Passing an Variable from one PHP File to another

I'm working on an image resizer, to create thumbnails for my page. The resizer works on principle of include a DIRECT link to the image. But what I want to do is put in the PHP Variable in the URL string, so that it points to that file and resizes it accordingly.
My code is as follows :
<img src="thumbnail.php?image=<?php echo $row_select_property['image_url']; ?>
Image Resize :
<?php
// Resize Image To A Thumbnail
// The file you are resizing
$image = '$_GET[image_url]';
//This will set our output to 45% of the original size
$size = 0.45;
// This sets it to a .jpg, but you can change this to png or gif
header('Content-type: image/jpeg');
// Setting the resize parameters
list($width, $height) = getimagesize($image);
$modwidth = $width * $size;
$modheight = $height * $size;
// Creating the Canvas
$tn= imagecreatetruecolor($modwidth, $modheight);
$source = imagecreatefromjpeg($image);
// Resizing our image to fit the canvas
imagecopyresized($tn, $source, 0, 0, 0, 0, $modwidth, $modheight, $width, $height);
// Outputs a jpg image, you could change this to gif or png if needed
imagejpeg($tn);
?>
What I am trying to do is pass on the variable "image=" to the Thumbnail script. At the moment I am passing it through the URL string, but it doesnt seem to load the graphic.
I'll try expand on this more, should you have questions as I am finding it a little difficult to explain.
Thanks in advance.
I suspect at least part of the problem is that your existing...
$image = '$_GET[image_url]';
...line is creating a text string, rather than getting the contents of the 'image_url' query string. Additionally, your passing in the image name as "?image=" in the query string, so you should simply use "image", not "image_url".
As such, changing this to...
$image = $_GET['image'];
...should at least move things along.
Change it
$image = '$_GET[image_url]';
to
$image = $_GET['image'];
$image = '$_GET[image_url]';
should be
$image = $_GET['image'];

I'm working on a website that sells different artwork, what's the best way to handle different image sizes?

I'm working on a website that will allow users to upload and sell their artwork in different sizes. I was wondering what the best way would be to handle the different file sizes automatically. A few points I was curious on:
How to define different size categories (small, medium, large) in such a way that I'll be able to dynamically re-size images with proportional dimensions.
Should I store actual jpegs of the different sizes for download? Or would it be easier to generate these different sizes for download on the fly
My thumbnails will be somewhat larger than your average thumbnails, should I store a second 'thumbnail image' with the sites watermark overlaying it? Or once again, generate this on the fly?
All opinions, advice are greatly appreciated!
I do something like this with aarongriffin.co.uk.
There, some images are resized on the fly the first time they are requested, and then they are stored; whilst others are generated at upload time. Images that tend to be requested in groups (i.e. thumbnails) are generated at upload time, and images that tend to be displayed one at a time are generated on the fly. This has worked well for me, but that's a site without too much traffic.
I'm working in Python and Django, so I use sorl-thumbnail for this. In PHP you've got access to the various imagecreatefrom* functions that do (sort of) the same thing.
I generate watermarked versions of photos (if a particular album should be watermarked), and store those instead of unwatermarked copies.
you can check php thumbnails for this. Here's a code snippet that maybe useful.
<?php
# Constants
define(IMAGE_BASE, '/var/www/html/mbailey/images');
define(MAX_WIDTH, 150);
define(MAX_HEIGHT, 150);
# Get image location
$image_file = str_replace('..', '', $_SERVER['QUERY_STRING']);
$image_path = IMAGE_BASE . "/$image_file";
# Load image
$img = null;
$ext = strtolower(end(explode('.', $image_path)));
if ($ext == 'jpg' || $ext == 'jpeg') {
$img = #imagecreatefromjpeg($image_path);
} else if ($ext == 'png') {
$img = #imagecreatefrompng($image_path);
# Only if your version of GD includes GIF support
} else if ($ext == 'gif') {
$img = #imagecreatefrompng($image_path);
}
# If an image was successfully loaded, test the image for size
if ($img) {
# Get image size and scale ratio
$width = imagesx($img);
$height = imagesy($img);
$scale = min(MAX_WIDTH/$width, MAX_HEIGHT/$height);
# If the image is larger than the max shrink it
if ($scale < 1) {
$new_width = floor($scale*$width);
$new_height = floor($scale*$height);
# Create a new temporary image
$tmp_img = imagecreatetruecolor($new_width, $new_height);
# Copy and resize old image into new image
imagecopyresized($tmp_img, $img, 0, 0, 0, 0,
$new_width, $new_height, $width, $height);
imagedestroy($img);
$img = $tmp_img;
}
}
# Create error image if necessary
if (!$img) {
$img = imagecreate(MAX_WIDTH, MAX_HEIGHT);
imagecolorallocate($img,0,0,0);
$c = imagecolorallocate($img,70,70,70);
imageline($img,0,0,MAX_WIDTH,MAX_HEIGHT,$c2);
imageline($img,MAX_WIDTH,0,0,MAX_HEIGHT,$c2);
}
# Display the image
header("Content-type: image/jpeg");
imagejpeg($img);
?>

Categories