NerdsTalk
NerdsTalk

Reputation: 1

How to crop JPG and PNG with transparent background on JS / jQuery

I'm using a plugin named "jcrop", it's pretty nice, you can see it here:

http://howhack.com/crop/demos/crop2.php

The issue is this plugin do not support png with transparent backgrounds.

Is there a similar script/plugin in javascript / jQuery that supports png with transparent backgrounds?

I need this rectangle thing with aspect ratio 16:9 and a final image always 640x360, that's why I'm trying to use this "jcrop".

Upvotes: 0

Views: 7371

Answers (2)

Xenethyl
Xenethyl

Reputation: 3199

I'm assuming the plugin does the image editing on the server via PHP? If so, you need to make a few special calls to preserve alpha transparency in PNG images:

$x = $_GET["x"];
$y = $_GET["y"];
$w = $_GET["w"];
$h = $_GET["h"];

// Load the original image.
$img = imagecreatefrompng($img_path);
imagealphablending($img, true);

// Create a blank canvas for the cropped image.
$img_cropped = imagecreatetruecolor($w, $h);
imagesavealpha($img_cropped, true);
imagealphablending($img_cropped, false);
$transparent = imagecolorallocatealpha($img_cropped, 0, 0, 0, 127);
imagefill($img_cropped, 0, 0, $transparent);

// Crop the image and store the data on the blank canvas.
imagecopyresampled($img_cropped, $img, 0, 0, $x, $y, $w, $h, $w, $h); // or imagecopy()

// Save the image.
imagepng($img_cropped, "image_cropped.png", 2);

// Free memory.
imagedestroy($img);
imagedestroy($img_cropped);

This is touched on a few times in the discussion for PHP's imagecopyresampled() here.

Upvotes: 6

Alex
Alex

Reputation: 3790

you can do the with canvas so much easier and if you want to save it you just send the raw canvas data to the server via post? http://www.nihilogic.dk/labs/canvas2image/

But if you want to use this plugin, what I would suggest is that you look at your server's php configuration. A lot of servers still only support jpeg and gif as part of their default php configurations. If you want to check this make a php file with this code in it:

phpinfo();

?>

and then upload and view it on your server. you should look for "libpng" on the page: http://www.php.net/manual/en/image.requirements.php

Upvotes: 0

Related Questions