Her*_*der 9 php image-processing
我需要一种方法(使用内置的PHP库)从URL下拉图像并将其保存到本地磁盘,调整大小/缩放WIDTH到150px.我一直在尝试这个:
function makeThumbnails($updir, $img, $id)
{
$thumbnail_width = 134;
$thumbnail_height = 189;
$thumb_beforeword = "thumb";
$arr_image_details = getimagesize("$updir" . $id . '_' . "$img"); // pass id to thumb name
$original_width = $arr_image_details[0];
$original_height = $arr_image_details[1];
if ($original_width > $original_height) {
$new_width = $thumbnail_width;
$new_height = intval($original_height * $new_width / $original_width);
} else {
$new_height = $thumbnail_height;
$new_width = intval($original_width * $new_height / $original_height);
}
$dest_x = intval(($thumbnail_width - $new_width) / 2);
$dest_y = intval(($thumbnail_height - $new_height) / 2);
if ($arr_image_details[2] == 1) {
$imgt = "ImageGIF";
$imgcreatefrom = "ImageCreateFromGIF";
}
if ($arr_image_details[2] == 2) {
$imgt = "ImageJPEG";
$imgcreatefrom = "ImageCreateFromJPEG";
}
if ($arr_image_details[2] == 3) {
$imgt = "ImagePNG";
$imgcreatefrom = "ImageCreateFromPNG";
}
if ($imgt) {
$old_image = $imgcreatefrom("$updir" . $id . '_' . "$img");
$new_image = imagecreatetruecolor($thumbnail_width, $thumbnail_height);
imagecopyresized($new_image, $old_image, $dest_x, $dest_y, 0, 0, $new_width, $new_height, $original_width, $original_height);
$imgt($new_image, "$updir" . $id . '_' . "$thumb_beforeword" . "$img");
}
}
Run Code Online (Sandbox Code Playgroud)
这看起来很有希望,但我无法弄清楚如何使用它,然后它是否会做我想要的.关注/需求:
($updir, $img, $id)- $updir文件的位置是什么?或者我想要保存的位置?是$img文件句柄还是文件名?还是文件的新名称?什么是$id?作者没有给出任何样本用法.data:image/jpeg;base64,/9j/4AAQ....实现这一目标的最佳方法是什么?
fly*_*ndi 32
这样做:
function Thumbnail($url, $filename, $width = 150, $height = true) {
// download and create gd image
$image = ImageCreateFromString(file_get_contents($url));
// calculate resized ratio
// Note: if $height is set to TRUE then we automatically calculate the height based on the ratio
$height = $height === true ? (ImageSY($image) * $width / ImageSX($image)) : $height;
// create image
$output = ImageCreateTrueColor($width, $height);
ImageCopyResampled($output, $image, 0, 0, 0, 0, $width, $height, ImageSX($image), ImageSY($image));
// save image
ImageJPEG($output, $filename, 95);
// return resized image
return $output; // if you need to use it
}
Run Code Online (Sandbox Code Playgroud)
像这样使用它:
Thumbnail("http://cdn.cutestpaw.com/wp-content/uploads/2013/01/l-Cute-Kitten.jpg", "kitten.jpg");
Run Code Online (Sandbox Code Playgroud)
这里的技巧是使用PHP的内部自动文件检测来处理传入的流 ImageCreateFromString