PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, October 10, 2022

[FIXED] How to use imagescale and retain appearance of edge "pixels"

 October 10, 2022     gd, image-scaling, php     No comments   

Issue

So I have a 3x3 pixel image using imagecreate. I want to scale up the image with imagescale while maintaining the look of a 3x3 grid of "pixels". However, the pixels on the right and bottom edge are not the same size.

Here is my code and output image:

<?php

$image = imagecreate(3, 3);
imagecolorallocate($image, 0, 0, 255);
$red = imagecolorallocate($image, 255, 0, 0);
imagesetpixel($image, 0, 0, $red);
imagesetpixel($image, 1, 1, $red);
imagesetpixel($image, 2, 2, $red);

imagepng(imagescale($image, 200, 200, IMG_NEAREST_NEIGHBOUR));

header("Content-Type: image/png");

This is my output:

enter image description here

Notice how the bottom-right pixel is cut off. I kept playing with the numbers for the new dimensions and arrived at 256x256 at which point the pixels are all the same size.

This is the output after using 256x256:

enter image description here

My question is: How can I derive the dimensions to use for the resized image with the effect I described?

Bonus question: Is an alternative method which will allow me to resize to an arbitrary size and keep the pixels approximately the same size?


Solution

I would use imagecopyresampled to achieve this.

http://php.net/manual/en/function.imagecopyresampled.php

<?php
    $width = 3;
    $height = 3;
    $image = imagecreate($width, $height);
    imagecolorallocate($image, 0, 0, 255);
    $red = imagecolorallocate($image, 255, 0, 0);
    imagesetpixel($image, 0, 0, $red);
    imagesetpixel($image, 1, 1, $red);
    imagesetpixel($image, 2, 2, $red);

    $new_width = 200;
    $new_height = 200;
    $dst = imagecreatetruecolor($new_width, $new_height);
    imagecopyresampled($dst, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
    imagepng($dst);

    header("Content-Type: image/png");


Answered By - Daisuke Tahara
Answer Checked By - Marilyn (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing