Converting images from png to jpeg

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Cytrus
Forum Newbie
Posts: 2
Joined: Mon May 18, 2009 10:01 am

Converting images from png to jpeg

Post by Cytrus »

I have a problem with saving PNG images in JPEG format with a partially transparent elements. In areas of partial transparency is dimming the picture to black, what is not correctly. These files can be seen as the land of hair became dark blue.
included file
included file
test.png (14.17 KiB) Viewed 128 times
resulted file
resulted file
test.jpg (2.74 KiB) Viewed 128 times

Code: Select all

 
$image = imagecreatefrompng('test.png');
imagejpeg($image, 'test.jpg');
 
To resolve this problem?
Defiline
Forum Commoner
Posts: 59
Joined: Tue May 05, 2009 5:34 pm

Re: Converting images from png to jpeg

Post by Defiline »

JPEG does not support alpha-channel.
You can manually convert PNG to JPEG.
For example:
1. Get the alpha-value of a pixel
2. Using RGB specification you should calcuale color value
3. Replace it using imagesetpixel
4. Look at 1.

Code: Select all

for($x = 1; $x < $width; $x++) {
    /*
     * Getting values
     */
    for($y = 1; $y < $height; $y++) {
         /*****************/
    }
}
Cytrus
Forum Newbie
Posts: 2
Joined: Mon May 18, 2009 10:01 am

Re: Converting images from png to jpeg

Post by Cytrus »

I used your advice and step-by-step cut out to the alpha channel, but nothing changed. This file is identical to the result obtained in previous attempts. Obviously, the problem in the function imagejpeg - it not correctly stores some data. I know that in jpeg format of the data is lost and the image becomes more blurred, but in this case, vice versa: at the edges of the image was too sharp.

Code: Select all

 
$image = imagecreatefrompng('test.png');
for($x = 0, $lx = imagesx($image); $x < $lx; $x++)
    for($y = 0, $ly = imagesy($image); $y < $ly; $y++){
        $color = imagecolorat($image, $x, $y);
        $params = imagecolorsforindex  ($image, $color);
        imagesetpixel($image, $x, $y, imagecolorallocate($image, $params['red'], $params['green'], $params['blue']));
}
//imagesavealpha($image, false);
imagejpeg($image, 'test.jpg');
 
Can I save the data in jpeg format by using other functions, or functions of other libraries that are supported in a PHP?
Last edited by Benjamin on Tue May 19, 2009 9:51 am, edited 1 time in total.
Reason: Changed code type from text to php.
Post Reply