简体   繁体   中英

PHP: Create Thumbnail Image Using X,Y Coordinates

How can I take a 500x500 (or any sized) image that has been uploaded to the server and generate a new image from defined specific x,y coordinates? For example (0,0) to (50,0); (0,50) to (50,50). Rather than resizing an image down to 50x50px, I want to grab the top left part of an image and in a sense "crop" it to use as a thumbnail.

How can I go about doing this in PHP?

You want to use imagecopy . First create an image with the dimensions you want and then use imagecopy to a portion of the source image into the new image:

// use whatever mechanism you prefer to load your source image into $image
$width = 50;
$height = 50;
// Define your starting coordinates in the source image.
$source_x = 20;
$source_y = 100;
$new_image = imagecreatetruecolor($width, $height);
imagecopy($new_image, $image, 0, 0, $source_x, $source_y, $width, $height);
// Now $new_image has the portion cropped from the source and you can output or save it.
imagejpeg($new_image);

http://www.php.net/manual/en/function.imagick-cropthumbnailimage.php#81547

$image = new Imagick($path."test1.jpg");

$image->cropThumbnailImage(160,120); // Crop image and thumb

$image->writeImage($path."test1.jpg");

I've seen a few ways to do this. If you want to generate the thumbs on the fly you could use:

function make_thumb($src,$dest,$desired_width)
{

  /* read the source image */
  $source_image = imagecreatefromjpeg($src);
  $width = imagesx($source_image);
  $height = imagesy($source_image);

  /* find the "desired height" of this thumbnail, relative to the desired width  */
  $desired_height = floor($height*($desired_width/$width));

  /* create a new, "virtual" image */
  $virtual_image = imagecreatetruecolor($desired_width,$desired_height);

  /* copy source image at a resized size */
  imagecopyresized($virtual_image,$source_image,0,0,0,0,$desired_width,$desired_height,$width,$height);

  /* create the physical thumbnail image to its destination */
  imagejpeg($virtual_image,$dest);
}

You can also set the quality parameter in the imagejpeg function.

Or if you want to save the image thumb to a directory I would look at:

http://bgallz.org/270/php-create-thumbnail-images/

or

http://www.imagemagick.org/script/index.php

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