Wednesday, 4 September 2013

Translating selection coordinates from a downscaled image

Translating selection coordinates from a downscaled image

I'm building a simple image cropping utility for a website.
I'm having a small problem: each time I do it there's distortion (my
selection coordinates are roughly estimated so the image is drawn with
wrong dimensions for example).
I sketched this to let you see what I mean:

Here's some code to help you get what I'm trying to achieve:
//Get the new coordinates to crop the image.
$x1 = $request->getPost('x1');
$y1 = $request->getPost('y1');
$x2 = $request->getPost('x2');
$y2 = $request->getPost('y2');
$w = $request->getPost('w');
$h = $request->getPost('h');
$croptool_width = $request->getPost('croptool_width');
$croptool_height = $request->getPost('croptool_height');
$original_width = $request->getPost('original_width');
$original_height = $request->getPost('original_height');
$infos = pathinfo($original_image_location);
$extension = strtolower($infos['extension']);
switch($extension) {
case 'gif':
$sourceImage = imagecreatefromgif($original_image_location);
break;
case 'jpg':
case 'jpeg':
$sourceImage = imagecreatefromjpeg($original_image_location);
break;
case 'png':
$sourceImage = imagecreatefrompng($original_image_location);
break;
}
// Take croptool's dimension, transpose selection coordinates to fit
the original image.
$scale = $original_height / $original_width;
// $scale = $croptool_height / $croptool_width;
$scaled_x1 = $x1 * $scale;
$scaled_y1 = $y1 * $scale;
$scaled_x2 = $x2 * $scale;
$scaled_y2 = $y2 * $scale;
// Crop selection and save to disk
$cropImage =
imagecreatetruecolor(Model_Wineries::getCoverImageWidth(),
Model_Wineries::getCoverImageHeight());
imagecopyresampled(
$cropImage, $sourceImage,
0, 0,
$scaled_x1, $scaled_y1,
Model_Wineries::getCoverImageWidth(),
Model_Wineries::getCoverImageHeight(),
$scaled_x2, $scaled_y2
);
if (file_exists($cover_image_location))
unlink($cover_image_location);
imagejpeg($cropImage, $cover_image_location, 90);
chmod($cover_image_location, 0777);
if (file_exists($original_image_location))
unlink($original_image_location);
The part I'm having trouble figuring out is how to properly calculate the
$scale variable.
$croptool_width and $croptool_height are both the downscaled dimensions.
$original_... are the original ones.
Could anybody help me please?
Thanks!

No comments:

Post a Comment