[英]PHP resize image on server and return via ajax
我有以下PHP代码来调整图像大小(我知道该图像将是png,因此无需检查...)
// The file
//$filename = $_POST['original'];
$filename = 'planets.png';
// Set a maximum height and width
$width = 200;
$height = 200;
// Content type
header('Content-Type: image/png');
// Get new dimensions
list($width_orig, $height_orig) = getimagesize($filename);
$ratio_orig = $width_orig/$height_orig;
if ($width/$height > $ratio_orig) {
$width = $height*$ratio_orig;
} else {
$height = $width/$ratio_orig;
}
// Resample
$image_p = imagecreatetruecolor($width, $height);
imagecreatefrompng($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
// Output
imagepng($image_p);
但是,我希望能够通过ajax将其返回到我的页面...请参见下面的代码:
<div data-img-src="planets.png"></div>
<script type="text/javascript">
$("div[data-img-src]").each( function() {
$.ajax({
type: "POST",
url: "/image-resize.php",
data: {
original: $(this).attr("data-img-src")
},
dataType: "html",
success: function(result) {
$(this).append(result);
}
});
});
</script>
任何想法,我需要做些什么来使这项工作?
编辑!
或者,这是达到相同预期结果的可接受方法吗?
$("div[data-img-src]").each( function() {
$(this).append("<img src='/image-resize.php?original="+$(this).attr("data-img-src")+"' />");
// COUPLED WITH $_GET... in the php
});
this
在AJAX功能的情况下并不是指的元素。 您可以使用以下代码更正此问题:
$("div[data-img-src]").each( function() {
var element = $(this);
$.ajax({
type: "POST",
url: "/image-resize.php",
data: {
original: element.attr("data-img-src")
},
dataType: "html",
success: function(result) {
element.append(result);
}
});
});
另外,您的PHP脚本是否肯定会输出HTML?
您为什么不使用TimThumb? 老实说,似乎根本不需要AJAX请求服务器。
该代码的作用是在页面上创建一个隐藏的img,将其宽度和高度存储为变量,计算出较大的(宽度或高度),然后返回裁剪的img。
您的基本目录中将需要timthumb.php,此代码才能正常工作。 我已将您原始的DIV元素更改为IMG元素,因为显然DIV无法接收SRC属性以将其转换为图像(不过您当然可以更改下面的代码以将图像输出为DIV的背景图像)。
$("img[data-img-src]").each( function() {
imgSrc = $(this).attr("data-img-src");
$('body').append('<img class="hidden-img" src="'+imgSrc+'" style="visibility:hidden;>');
imgWidth = $('.hidden-img').outerWidth();
imgHeight = $('.hidden-img').outerHeight();
imgString = '/timthumb.php?src='+imgSrc;
if(imgWidth > imgHeight){
imgString = imgString+'&h=200&q=90';
} else {
imgString = imgString+'&w=200&q=90';
}
$('.hidden-img').remove();
$('body').append('<img src="'+imgString+'">');
});
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.