问题:设计网站时,我有时使用width:xxx;在图像上。这样我就能够调整图像。但是,这会造成规模上的开销。使用width属性自动调整图像大小并将其保存在计算机上
解决方案:自动获取宽度为propery的所有图像。将它们的大小调整为:width属性保持尺寸。在计算机上将该文件保存为.gif文件。
有谁知道一个好的解决方案?
问题:设计网站时,我有时使用width:xxx;在图像上。这样我就能够调整图像。但是,这会造成规模上的开销。使用width属性自动调整图像大小并将其保存在计算机上
解决方案:自动获取宽度为propery的所有图像。将它们的大小调整为:width属性保持尺寸。在计算机上将该文件保存为.gif文件。
有谁知道一个好的解决方案?
可以使用GD做(如果你有GD或GD2在你的PHP安装目录启用) http://php.net/image
<?php
function resizeImage($image,$width=null,$height=null){
if(!$width and !$height) return false;
$info = getimagesize($image);
if(!$height) $height = $width/$info[0]*$info[1];
if(!$width) $width = $height/$info[1]*$info[0];
$new = newEmptyImage($width, $height);
$resource = imagecreatefromgif($image);
imagecopyresampled($new,$resource,0,0,0,0,$width,$height,$info[0],$info[1]);
return imagegif($new,$image);
}
function newEmptyImage($width,$height){
$new = imagecreatetruecolor($width,$height);
imagealphablending($new, false);
imagesavealpha($new, true);
$bg = imagecolorallocatealpha($new,0,0,0,127);
imagefill($new,0,0,$bg);
return $new;
}
?>
现在你可以简单地调用resizeImage("example.gif",120);
我已经写了一段JavaScript代码代码使用<canvas>
替换调整大小后的文档中的所有图像。 小提琴:http://jsfiddle.net/F2LK2/
function imageToFit(img) {
var width = img.width;
var height = img.height;
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
canvas.width = width;
canvas.height = height;
context.drawImage(img, 0, 0, width, height);
img.parentNode.replaceChild(canvas, img);
}
window.onload = function(){
var image = document.getElementsByTagName("img");
for(var i=image.length-1; i>=0; i--){
//Backwards, because we replace <img> by <canvas>
imageToFit(image[i]);
}
}
如果你有兴趣在脚本Canvas元素,看看Mozilla的Canvas tuturial。
这将需要比JavaScript更好的编程语言。 –
@SamuelLiew - 将PHP添加为标记意味着当OP没有将其要求限制于此时,现在所有的答案都是PHP解决方案。我想如果OP没有提到编程语言,那么你应该可以自由地用PHP解决方案来回答问题,但是不要把问题改为PHP。 – Curt
@DanBizdadea JavaScript也可以使用Canvas或SVG来处理图像。 –