简体   繁体   中英

PHP & JS - Jcrop - chosen PNG image has black background

When I choose PNG file with transparent background in Jcrop container it is displayed with black background. When I crop it and save it, it is saved as .png file, but with black background as it was displayed in crop container.

JS:

$('#image').Jcrop({
    bgColor: 'transparent',
    aspectRatio: 1,
    minSize: [180, 180],
    maxSize: [20000, 20000],
    onSelect: updateCoords,
    onChange: updateCoords,
    boxWidth: $('.modal-body', $imageUploadModal).width()
});

PHP for saving images:

$target_w = $target_h = 400;

$src = $request->request->get('src');
$x = $request->request->get('x');
$y = $request->request->get('y');
$w = $request->request->get('w');
$h = $request->request->get('h');

ini_set('memory_limit', -1);

$img_r = imagecreatefrompng($src);
imagealphablending($img_r, true);

$dst_r = ImageCreateTrueColor($target_w, $target_h);

imagecopyresampled($dst_r, $img_r, 0, 0, $x, $y, $target_w, $target_h, $w, $h);

$randomStringGenerator = new RandomStringGenerator();
$filename = '/profile-pictures/'.$randomStringGenerator->generate(50).'.png';

imagepng($dst_r, $filename);
imagedestroy($img_r);
imagedestroy($dst_r);

ini_restore('memory_limit');

Any ideas what I could be missing? bgColor as I saw in multiple answers as solution does not have any effect and is not fixing the issue.

It could be because of imagecreatetruecolor

Quoting example gave in first user contributed note on the manual page :

If you want to create a transparent PNG image, where the background is fully transparent, and all draw operations happen on-top of this, then do the following:

"Richard Davey"

<?php
    $png = imagecreatetruecolor(800, 600);
    imagesavealpha($png, true);

    $trans_colour = imagecolorallocatealpha($png, 0, 0, 0, 127);
    imagefill($png, 0, 0, $trans_colour);

    $red = imagecolorallocate($png, 255, 0, 0);
    imagefilledellipse($png, 400, 300, 400, 300, $red);

    header("Content-type: image/png");
    imagepng($png);
?>

Meaning when you creatre your "host" image to copy cropped image to, you say it has a transparent background

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM