Hendrik
Hendrik

Reputation: 4929

Automatically resize images with width property and save them on computer

Problem: When designing the website I sometimes used width: xxx; on images. That way I was able to adjust the images. However, that creates overhead in size.

Solution: Automatically fetch all images which have a width: propery. Resize them to that :width property keeping the dimensions. Save the file as a .gif on the computer.

Does anyone know a good solution?

Upvotes: 3

Views: 879

Answers (2)

SparK
SparK

Reputation: 5211

You can do it using GD (if you have GD or GD2 enabled on your php instalation) 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;
    }
?>

now you can simply call resizeImage("example.gif",120);

Upvotes: 2

Rob W
Rob W

Reputation: 349132

I've written a piece of JavaScript code to replace all images in a document by a resized-to-fit version, using <canvas>. Fiddle: 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]);
    }
}

If you're interested in scripting the Canvas element, have a look at Mozilla's Canvas tuturial.

Upvotes: 1

Related Questions