Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP image resize using nearest-neighbor interpolation?

I have a 16x16 sprite in PNG or GIF image format, and would like to display it on a website at 64 x 64 in all its pixelated glory. In Firefox 3.6+ and IE I can do this easily with CSS using image-rendering and -ms-interpolation-mode, but as this doesn't work in all browsers I'd like to resize the image on the fly using PHP instead. What's the best way to resize images using nearest-neighbor interpolation in PHP?

like image 805
shipshape Avatar asked Dec 25 '10 16:12

shipshape


2 Answers

If you want to keep the pixelation during your resize, you will want to do something like this using the GD library:

<?php
// create GD image resource from source image file
$src = imagecreatefromgif('test.gif');

// create new GD image resource with indexed color
$dest = imagecreate(64, 64);

// copy/resize image without resampling
imagecopyresized($dest, $src, 0, 0, 0, 0, 64, 64, 16, 16);

// output result
header('Content-type: image/gif');
imagegif($dest);
?>

I have tested the code, and the pixelation remains in tact. You will have to adapt the code to also accept png files as input, which should be fairly easy since each of the GD gif functions also have corresponding png functions. Hope this helps.

like image 51
dqhendricks Avatar answered Oct 13 '22 02:10

dqhendricks


You can use the ImageMagick project, if u need resize GIFs too.

You can use GD, but, it's possible that u lose some EXIF data.

The KusabaX Project has a great function to convert image. Check the file "/inc/func/posts.php" at line 58. ;-)

like image 23
fvox Avatar answered Oct 13 '22 01:10

fvox