0

We get a jpg that contains a drawing made of black lines. We do crop it, rotate it, make the white transparent, then finally resize it to a standard width.

Before I resize it, the image (in $src) is just what I want it to be with transparency in the right places. After resampling it, the image ($out) is back to having a white background. (The commented out lines are some of the things I tried.) Before I found an answer to a similar problem, I wasn't changing the settings for alpha blending and alpha save and there was at least some very noisy transparency.

How can I get the resampled image to change the white to transparent?

EDIT: In $out I see that most pixels are 255, 255, 255. Some are 252, 252, 252. A few are 245, 245, 245. Those are the only 3 values I have seen in $out. I'm not understanding why this would be the case for $out but not for $src.

<?php

$imgname = "../assets/Sample.jpg";
$src = imagecreatefromjpeg($imgname);

$src = imagecropauto($src, IMG_CROP_WHITE);
$white = imagecolorallocate($src, 255, 255, 255);
imagecolortransparent($src, $white);
$src = imagerotate($src, -90, 0);

// Resample
$width = imagesx($src);
$height = imagesy($src);
$percent = 270/$width;
$new_width = $width * $percent;
$new_height = $height * $percent;

$out = imagecreatetruecolor($new_width, $new_height);
//imagefill($out, 0,0, imagecolorallocate($out, 255, 255, 255));
imagealphablending( $out, false );
imagesavealpha( $out, true );
imagecopyresampled($out, $src, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
$white2 = imagecolorallocate($out, 255, 255, 255);
imagecolortransparent($out, $white2);



    header("Content-type: image/png");
//    imagepng($src);
    imagepng($out);
?>
Community
  • 1
  • 1
Mark Kasson
  • 1,600
  • 1
  • 15
  • 28

1 Answers1

0

The problem with drawing in JPEG is that the compression process slightly changes values. This is not generally noticeable in photos but shows up in drawings.

If you know everything is black or write, you should convert the pixels that are close-to-black to black and those that are close-to-white to white.

user3344003
  • 20,574
  • 3
  • 26
  • 62
  • I thought it might be a JPEG issue, but when I output $src (on which everything is performed except the resample), it comes out perfectly. Plus, not even the #FFFFFF gets changed to transparent in $out. – Mark Kasson Mar 22 '16 at 19:20