Html 使用“宽度”属性自动调整图像大小并将其保存在计算机上

Html 使用“宽度”属性自动调整图像大小并将其保存在计算机上,html,css,image,image-resizing,Html,Css,Image,Image Resizing,问题:在设计网站时,我有时使用宽度:xxx;在图像上。这样我就可以调整图像了。然而,这会在规模上产生开销 解决方案:自动获取宽度为:propery的所有图像。将尺寸调整为:宽度属性,保留尺寸。将文件另存为计算机上的.gif格式 有人知道一个好的解决方案吗?您可以使用GD(如果您在php安装中启用了GD或GD2) 现在您只需调用resizeImage(“example.gif”,120)我编写了一段JavaScript代码,使用将文档中的所有图像替换为调整大小以适合的版本小提琴: 功能图像编

问题:在设计网站时,我有时使用宽度:xxx;在图像上。这样我就可以调整图像了。然而,这会在规模上产生开销

解决方案:自动获取宽度为:propery的所有图像。将尺寸调整为:宽度属性,保留尺寸。将文件另存为计算机上的.gif格式

有人知道一个好的解决方案吗?

您可以使用GD(如果您在php安装中启用了GD或GD2)



现在您只需调用
resizeImage(“example.gif”,120)

我编写了一段JavaScript代码,使用
将文档中的所有图像替换为调整大小以适合的版本小提琴:

功能图像编辑(img){
变量宽度=img.width;
var高度=img高度;
var canvas=document.createElement('canvas');
var context=canvas.getContext('2d');
画布宽度=宽度;
canvas.height=高度;
绘图图像(img,0,0,宽度,高度);
parentNode.replaceChild(canvas,img);
}
window.onload=函数(){
var image=document.getElementsByTagName(“img”);
对于(var i=image.length-1;i>=0;i--){
//向后,因为我们用
imageToFit(图像[i]);
}
}

如果您对编写Canvas元素的脚本感兴趣,请查看Mozilla的。

这需要一种比javascript更好的编程语言。@DanBizdadea javascript还可以处理图像,使用Canvas或SVG。我假设问题的一部分是客户端仍然需要获取完整的大图像,并且需要一个一次性的过程来获取、调整和保存调整大小的图像,以便将来可以请求较小的图像。不过,我可能没有抓住问题的重点。:)@Chris OP在问题中明确添加了
JavaScript
标记。我将这个问题解释为:“当用户保存我的图像时,我希望图像的大小与显示的大小完全一致”。正确。我在看“然而,这会在大小上产生开销”。我把这解释为担心在转会时的开销。不过你很可能是对的。我现在就让OP来操心这件事。:)使用JavaScript并不意味着它是客户端的,记住Node.js
<?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;
    }
?>
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]);
    }
}