简体   繁体   中英

PHP - cropping image with imagecopyresampled()?

I'd like to crop an image using imagecreatetruecolor and it always crops it leaving black spaces, or the zoom is too big. I want the image to be exactly 191px wide and 90px high, so I also need to resize the image, as well as crop, because the ratio has to be kept. Well, there are some samples of the project:

在此输入图像描述

The resize script (simplified) goes like this:

$src_img=imagecreatefromjpeg($photoTemp);    
list($width,$height)=getimagesize($photoTemp);
$dst_img=imagecreatetruecolor(191, 90);
imagecopyresampled($dst_img, $src_img, 0, 0, $newImage['crop']['x'], $newImage['crop']['y'], $newImage['crop']['width'], $newImage['crop']['height'], $width, $height);

The $newImage['crop'] array includes:

['x'] => $_POST['inp-x']
['y'] => $_POST['inp-x']
['width'] => $_POST['inp-width']
['height'] => $_POST['inp-height']

But what I get is:

在此输入图像描述

Anyone sees, what I'm doing wrong?

Thanks, Mike.

you can do it too, I myself did it, and it works

(x1,y1)=> where crop starts

(x2,y2)=> where crop ends

$filename = $_GET['imageurl'];
$percent = 0.5;

list($width, $height) = getimagesize($filename);

$new_width  = $_GET['x2'] - $_GET['x1'];
$new_height = $_GET['y2'] - $_GET['y1'];

$image_p = imagecreatetruecolor($new_width, $new_height);
$image = imagecreatefromjpeg($filename);

imagecopyresampled($image_p, $image, 0, 0 , $_GET['x1'] , $_GET['y1'] , $new_width, $new_height, $new_width, $new_height);

// Outputs the image
header('Content-Type: image/jpeg');
imagejpeg($image_p, null, 100);

Try

<?php

$dst_img = imagecreatetruecolor($newImage['crop']['width'], $newImage['crop']['height']);

imagecopyresampled($dst_img, $src_img, 0, 0, $newImage['crop']['x'], $newImage['crop']['y'], 0, 0, $width, $height);

还有imagecrop函数,它允许您传入具有xywidthheight值的数组。

好吧,我自己发现了问题,代码应该是这样的:

imagecopyresampled($dst_img, $src_img, 0, 0, $newImage['crop']['x'], $newImage['crop']['y'], $newImage['newWidth'], 191, 90, $newImage['crop']['height']); 

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