PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label png. Show all posts
Showing posts with label png. Show all posts

Tuesday, October 11, 2022

[FIXED] How to change the filename displayed in the "Save as..." dialog from .php to .png

 October 11, 2022     gd, php, png     No comments   

Issue

A simple PHP script that I picked up from stackoverflow generates a PNG with a transparent background, writes some text on it then directly outputs it to the client browser:

$font = 25;
$string = 'My Text';
$im = @imagecreatetruecolor(300, 300);
imagesavealpha($im, true);
imagealphablending($im, false);
$white = imagecolorallocatealpha($im, 255, 255, 255, 127);
$red = imagecolorallocate($im, 255, 0, 0);
imagefill($im, 0, 0, $white);
$lime = imagecolorallocate($im, 204, 255, 51);
imagettftext($im, $font, 0, 0, 30, $red, "fonts/tt0588m_.ttf", $string);
header("Content-type: image/png");
imagepng($im);
imagedestroy($im);

The scope is to obtain a simple service that feeds an image based on the parameters passed to it via URL, such as Google Charts (e.g. this QR code image).

So far, so good, except that if I click on the image generated with the code above and want to save it, the browser doesn't recognize it as being a PNG image, but a PHP script (Save as type selector has this option only), as oposed to the Google Charts example, where the resource is clearly identified as a PNG file.

How do I achieve this correct resource identification by the browser?


Solution

Browser will use the filename from the URL as the default value in the "Save as..." dialog. You can type another name of course or save the file using the suggested name (text.php) and rename it afterwards.

You can use the Content-disposition header to "suggest" a filename to the browser. Here is an example:

header("Content-type: image/png");
header("Content-disposition: inline; filename=mytext.png");
  • inline suggests that browser should attempt to display the image. Change it to attachment to suggest that the browser should display the "Save as..." or similar dialog.
  • filename= should contain the filename of your choice.


Answered By - Salman A
Answer Checked By - Mary Flores (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Monday, October 10, 2022

[FIXED] how to resize an image for printing in php

 October 10, 2022     gd, php, png     No comments   

Issue

enter image description here

I have an image I am trying to force to standard 8.5 x 11 for printing. Because of how it is rendered, I could figure out a way to get img src="" to work and all of the php functions I found blew out the memory when getting even close.

<?php

$image = imagecreatefrompng('/var/www/localhost/htdocs/contactdb/2.png');

header('Content-type: image/png');

$black = imagecolorallocate($image, 0, 0, 0);
$font_path = '/var/www/localhost/htdocs/contactdb/arial.ttf';
$text = "This is a message!";
imagettftext($image, 100, 0, 275, 800, $black, $font_path, $text);

imagepng($image);

imagedestroy($image);
?>

Solution

If you want to resize your image on printing you can create a print.css. Include it in your html page with:

<link rel="stylesheet" href="print.css" screen="print">

..and then add your style property for the image that you want to be resized in print.css

img.yourimage
{
     width: newwidth;
     height: newheight;
}


Answered By - Emre Aydin
Answer Checked By - David Goodson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] Why is this PNG image rendered differently on Chrome and Firefox?

 October 10, 2022     browser, gd, image, php, png     No comments   

Issue

Here is the image url: Image

It gets yellow background on Firefox and green on Chrome and other browers.

Some screenshots:

On chrome:

chrome

On firefox:

firefox

When I try to save and look at it saved on desktop, it is green background.

Sorry, my english isn't good.


Solution

It is an APNG file. The main image (fallback) is green and the animation frame is yellow. Chrome doesn't handle the APNG chunks so it falls back on the main image. Here is a chunk listing; the acTL identifies it as an APNG.

# pngcheck -v *.png
File: BeMshNt.png (795 bytes)
  chunk IHDR at offset 0x0000c, length 13
    400 x 200 image, 8-bit palette, non-interlaced
  chunk acTL at offset 0x00025, length 8
    unknown private, ancillary, unsafe-to-copy chunk
  chunk PLTE at offset 0x00039, length 9: 3 palette entries
  chunk tRNS at offset 0x0004e, length 1: 1 transparency entry
  chunk IDAT at offset 0x0005b, length 295
    zlib: deflated, 32K window, maximum compression
  chunk fcTL at offset 0x0018e, length 26
    unknown private, ancillary, unsafe-to-copy chunk
  chunk fdAT at offset 0x001b4, length 300
    unknown private, ancillary, unsafe-to-copy chunk
  chunk tEXt at offset 0x002ec, length 27, keyword: Software
  chunk IEND at offset 0x00313, length 0
No errors detected in BeMshNt.png (9 chunks, 99.0% compression).


Answered By - Glenn Randers-Pehrson
Answer Checked By - Marilyn (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to calculate thickness of an object in PNG file using PHP GD library

 October 10, 2022     gd, image-processing, php, php-gd, png     No comments   

Issue

I have a PNG frame and I want to know its thickness. I am able to calculate the width/height of the image itself.

$frame = imagecreatefrompng('frame.png');
// get frame dimentions
$frame_width = imagesx($frame);
$frame_height = imagesy($frame);

But can't figure out a way to calculate thickness of frame, please see image below so see what I mean.

enter image description here

Any suggestions?


Solution

From the last answer it shows that there's no objects in a raster image file. However, you can do it by searching the first occurrence of transparent colour and the first occurrence of the non-transparent colour and calculate the distance of them (assumes that your image's blank area are all transparent).

Example code:

<?php
$img = imagecreatefrompng('./frame.png');//open the image
$w = imagesx($img);//the width
$h = imagesy($img);//the height

$nonTransparentPos = null;//the first non-transparent pixel's position
$transparentPos = null;//the first transparent pixel's position

//loop through each pixel
for($x = 0; $x < $w; $x++){
   for($y = 0; $y < $h; $y++){
        $color = imagecolorsforindex($img,imagecolorat($img,$x,$y));
        if($color['alpha'] < 127 && $nonTransparentPos === null){
            $nonTransparentPos = array($x,$y);
        }
        if($color['alpha'] === 127 && $transparentPos === null){
            $transparentPos = array($x,$y);
        }
   }
   //leave the loop if we have finished finding the two values.
   if($transparentPos !== null && $nonTransparentPos !== null){
        break;
   }
}
$length = $transparentPos[0]-$nonTransparentPos[0];//calculate the two point's x-axis distance
echo $length;
?>


Answered By - Licson
Answer Checked By - Marilyn (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to minimize and resize PNG images with transparency in php

 October 10, 2022     gd, php, png, transparency     No comments   

Issue

I have 512 * 512 big size PNG images with transparency.

How to create 256 * 256 PNG images with smaller file size, which also support transparency and maintaining quality.

EDIT: I'm using this code but the output image is cropped and not supporting transparency.

   $image = imagecreatefrompng("C:\Users\HP\htdocs\icon_hd.png");  // 512 * 512
    $bg = imagecreatetruecolor(256, 256);
    imagefill($bg, 0, 0, 0);
    imagealphablending($bg, TRUE);
    imagecopy($bg, $image, 0, 0, 0, 0, imagesx($image), imagesy($image));
    imagedestroy($image);
    $quality = 100;
    imagepng($bg, "C:\Users\HP\out_icon.png", 9);
    imagedestroy($bg);

Solution

You can use ImageMagick :

Simple example:

$inFile = "big_img.png";
$outFile = "small_img.png";
$image = new Imagick($inFile);
$image->thumbnailImage(256, 256);
$image->writeImage($outFile);

More info



Answered By - Alexander
Answer Checked By - Clifford M. (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How do I resize and convert an uploaded image to a PNG using GD?

 October 10, 2022     database, gd, image, php, png     No comments   

Issue

I want to allow users to upload avatar-type images in a variety of formats (GIF, JPEG, and PNG at least), but to save them all as PNG database BLOBs. If the images are oversized, pixelwise, I want to resize them before DB-insertion.

What is the best way to use GD to do the resizing and PNG conversion?

Edit: Sadly, only GD is available on the server I need to use, no ImageMagick.


Solution

<?php                                              
/*
Resizes an image and converts it to PNG returning the PNG data as a string
*/
function imageToPng($srcFile, $maxSize = 100) {  
    list($width_orig, $height_orig, $type) = getimagesize($srcFile);        

    // Get the aspect ratio
    $ratio_orig = $width_orig / $height_orig;

    $width  = $maxSize; 
    $height = $maxSize;

    // resize to height (orig is portrait) 
    if ($ratio_orig < 1) {
        $width = $height * $ratio_orig;
    } 
    // resize to width (orig is landscape)
    else {
        $height = $width / $ratio_orig;
    }

    // Temporarily increase the memory limit to allow for larger images
    ini_set('memory_limit', '32M'); 

    switch ($type) 
    {
        case IMAGETYPE_GIF: 
            $image = imagecreatefromgif($srcFile); 
            break;   
        case IMAGETYPE_JPEG:  
            $image = imagecreatefromjpeg($srcFile); 
            break;   
        case IMAGETYPE_PNG:  
            $image = imagecreatefrompng($srcFile);
            break; 
        default:
            throw new Exception('Unrecognized image type ' . $type);
    }

    // create a new blank image
    $newImage = imagecreatetruecolor($width, $height);

    // Copy the old image to the new image
    imagecopyresampled($newImage, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);

    // Output to a temp file
    $destFile = tempnam();
    imagepng($newImage, $destFile);  

    // Free memory                           
    imagedestroy($newImage);

    if ( is_file($destFile) ) {
        $f = fopen($destFile, 'rb');   
        $data = fread($f);       
        fclose($f);

        // Remove the tempfile
        unlink($destFile);    
        return $data;
    }

    throw new Exception('Image conversion failed.');
}


Answered By - Acuminate
Answer Checked By - Marilyn (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, October 9, 2022

[FIXED] How do I resize pngs with transparency in PHP?

 October 09, 2022     gd, php, png, resize     No comments   

Issue

I'm attempting to resize pngs with transparent backgrounds in PHP and the code samples I've found online don't work for me. Here's the code I'm using, advice will be much appreciated!

$this->image = imagecreatefrompng($filename);

imagesavealpha($this->image, true);
$newImage = imagecreatetruecolor($width, $height);

// Make a new transparent image and turn off alpha blending to keep the alpha channel
$background = imagecolorallocatealpha($newImage, 255, 255, 255, 127);
imagecolortransparent($newImage, $background);
imagealphablending($newImage, false);
imagesavealpha($newImage, true);

imagecopyresampled($newImage, $this->image, 0, 0, 0, 0, $width, $height,  $this->getWidth(), $this->getHeight());
$this->image = $newImage;  
imagepng($this->image,$filename);


Update By 'not working' I meant to say the background color changes to black when I resize pngs.


Solution

From what I can tell, you need to set the blending mode to false, and the save alpha channel flag to true before you do the imagecolorallocatealpha()

<?php
/**
 * https://stackoverflow.com/a/279310/470749
 * 
 * @param resource $image
 * @param int $newWidth
 * @param int $newHeight
 * @return resource
 */
public function getImageResized($image, int $newWidth, int $newHeight) {
    $newImg = imagecreatetruecolor($newWidth, $newHeight);
    imagealphablending($newImg, false);
    imagesavealpha($newImg, true);
    $transparent = imagecolorallocatealpha($newImg, 255, 255, 255, 127);
    imagefilledrectangle($newImg, 0, 0, $newWidth, $newHeight, $transparent);
    $src_w = imagesx($image);
    $src_h = imagesy($image);
    imagecopyresampled($newImg, $image, 0, 0, 0, 0, $newWidth, $newHeight, $src_w, $src_h);
    return $newImg;
}
?>

UPDATE : This code is working only on background transparent with opacity = 0. If your image have 0 < opacity < 100 it'll be black background.



Answered By - Dycey
Answer Checked By - David Marino (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, September 18, 2022

[FIXED] How to load .png images with image names listed in a .csv file to R

 September 18, 2022     csv, imagick, png, r     No comments   

Issue

I am using a simple code below to append multiple images together with the R magick package. It works well, however, there are many images to process and their names are stored in a .csv file. Could anyone advise on how to load the image names to the image_read function from specific cells in a .csv file (see example below the code)? So far, I was not able to find anything appropriate that would solve this.

library (magick)

pic_A <- image_read('A.png')
pic_B <- image_read('B.png')
pic_C <- image_read('C.png')

combined <- c(pic_A, pic_B, pic_C)
combined <- image_scale(combined, "300x300")
image_info(combined)
final <- image_append(image_scale(combined, "x120"))
print(final)
image_write(final, "final.png") #to save

enter image description here


Solution

Something like this should work. If you load the csv into a dataframe then, it's then straightforward to point the image_read towards the appropriate elements.

And the index (row number) is included in the output filename so that things are not overwritten each iteration.

library (magick)

file_list <- read.csv("your.csv",header = F)
names(file_list) <- c("A","B","C")

for (i in 1:nrow(file_list)){
pic_A <- image_read(file_list$A[i])
pic_B <- image_read(file_list$B[i])
pic_C <- image_read(file_list$C[i])

combined <- c(pic_A, pic_B, pic_C)
combined <- image_scale(combined, "300x300")
image_info(combined)
final <- image_append(image_scale(combined, "x120"))
print(final)
image_write(final, paste0("final_",i,".png")) #to save
}


Answered By - Jul
Answer Checked By - Marilyn (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, July 29, 2022

[FIXED] How would I load a PNG image using Win32/GDI (no GDI+ if possible)?

 July 29, 2022     c++, gdi, image, png, winapi     No comments   

Issue

Is it possible to load a PNG from a file into an HBITMAP using Win32 GDI functions? If not, what would be the lightest solution without using external libraries (like libpng)?


Solution

You can use the Windows Imaging Component to load PNG files (on Windows XP SP2 and later). See MSDN Magazine for an introduction on how to use the API and my blog post for a code sample that loads a PNG from an IStream and converts it to an HBITMAP.



Answered By - Bradley Grainger
Answer Checked By - Cary Denson (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to add dotted or dashed line to png in Python?

 July 29, 2022     image, line, png, python     No comments   

Issue

Hello I want a draw a dashed or dotted line to png, I couldn't find How can I do that, Can someone help ?

im = Image.new('RGB', (2000,2000),tuple(int(hex_color[i:i+2], 16) for i in (0, 2, 4))) print("...Saving...") im.save('C:\\Users\\th3m1s\\Desktop\\Lejant\\'+str(legend_code)+'.png', quality=100) Result is click here


Solution

Have you considered creating a new image with vertical lines as well as horizontal lines, slightly taller and wider than your original image, on which you paste your original image? That way you will have a dotted border and it works for every size.

This can be done as explained here: How do you composite an image onto another image with PIL in Python?

from PIL import Image,ImageDraw
#this is your own image
yourimage = Image.open('/home/vancha/Documenten/python/pillu/square.png', 'r')
img_w, img_h = yourimage.size
border_width = 5
#this is the new image which holds the stripes
borderimage = Image.new('RGBA', (2000+(border_width * 2), 2000+(border_width *2)), (255, 255, 255, 255))


# Draw the lines
draw = ImageDraw.Draw(borderimage)
#starts drawing vertical lines form the very top
start = 0
end = borderimage.height#width or height, doens't matter since the image is square
step_size = border_width*4

#starts from border_width * 2, so that the very top and very left aren't made black with lines
for x in range(border_width*2, borderimage.width, step_size):
    vertical_line = ((x, start), (x, end))
    #the width is the thickness of the "dots" in the border
    draw.line(vertical_line, fill=(0,0,0),width=border_width * 2)

    horizontal_line = ((start,x), (end, x))
    draw.line(horizontal_line, fill=(0,0,0),width=border_width *2)

#for good practice:
del draw


bg_w, bg_h = borderimage.size
#calculate the offset so that the image is centered
offset = ((bg_w - img_w) // 2, (bg_h - img_h) // 2)

#paste your old image over the one with the dots
borderimage.paste(yourimage, offset)

#save it wherever you want :)
borderimage.save('./border.png')

In your case, if you want your border to be 5px all the way around your image, and your image is 2000,2000, changing the size of the new image to be 2010 by 2010 leaves you with 5px to spare on both sides if you paste your own image in the center.



Answered By - Vancha
Answer Checked By - Katrina (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, July 26, 2022

[FIXED] How can you use PHP GD imagecrop on a PNG whilst maintaining transparency?

 July 26, 2022     crop, image, php, png, transparency     No comments   

Issue

Whenever I call PHP GD's imagecrop() on a PNG with transparency it is turning the transparent part black instead of maintaining it.

I have recently written a function to scale transparent PNGs whilst maintaining the transparency (see below), so I understand about using imagecopyresampled etc.

function scale_png($image, $resize_w = FALSE, $resize_h = FALSE, $alpha = 127)
{
    $src_w = imagesx($image);
    $src_h = imagesy($image);
    if (! $resize_w) {$resize_w = $src_w;}
    if (! $resize_h) {$resize_h = $src_h;}
    $output = imagecreatetruecolor($resize_w, $resize_h);
    imagealphablending($output, FALSE);
    imagesavealpha($output, TRUE);
    $transparent = imagecolorallocatealpha($output, 255, 255, 255, $alpha);
    imagefilledrectangle($output, 0, 0, $resize_w, $resize_h, $transparent);
    imagecopyresampled($output, $image, 0, 0, 0, 0, $resize_w, $resize_h, $src_w, $src_h);

    return $output;
}

This function above is working fine, but when I also try to do imagecrop() on the same PNG this is when I get the black background.

Is there any easy way of performing this crop successfully? I can't seem to find any good examples.

I would rather not have to write another complex function like the one above in order to crop the image out using x, y, w, h and imagecopyresampled() if possible, as it's a major ball ache.

Any GD boffins out there care to impart their valued knowledge on me?


Solution

The way I understand there is nothing complicated here, you have to save the alpha channels before performing the crop.

$img = imagecreatefrompng("./cover.png");
imagealphablending($img, false);
imagesavealpha($img, true);
$resource = imagecrop($img, ['x' => 0, 'y' => 0, 'width' => 500, 'height' => 500]);


Answered By - imal hasaranga perera
Answer Checked By - Cary Denson (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Monday, July 18, 2022

[FIXED] How can I convert PNG to GIF keeping the transparency?

 July 18, 2022     delphi, gif, graphics, png     No comments   

Issue

How can I convert PNG to GIF keeping the transparency?

I would have hoped that using the Assign( ) method would work but it doesn't seem to migrate transparency. In the GIF, it's represented as black.

    png:=TPngImage.Create;
    try
      png.LoadFromFile(sFile);
      // comes from file:  png.TransparencyMode;
      // comes from file:  png.Transparent

      // didn't help:  gif.Transparent:=true;

      gif.Assign(png);

      // didn't help:  gif.Transparent:=true;

      gif.SaveToFile('e:\tmp\out.gif');
    finally
      png.Free;
    end;

I haven't found a way to handle this in Delphi...

thanks!


Solution

It is possible to transfer an image from a PNG to a GIF. However, I don't recommend that you do so. The GIF format is substantially less capable than PNG. PNG supports RGBA color channels and partial transparency. GIF uses a 256 color palette and no support for partial transparency.

There are many libraries available that will make the best of a bad job and attempt to produce a GIF image that is close to the PNG image, but information will be lost.

The GIF format dates from the late 1980s and time has moved on. It has long since served its purpose. PNG is modern, capable and well supported. If it is possible to do so you should switch from GIF to using PNG.



Answered By - David Heffernan
Answer Checked By - David Goodson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, July 17, 2022

[FIXED] How to avoid aliasing when you place a GIF image over a PNG image?

 July 17, 2022     css, gif, image, png     No comments   

Issue

I have two images. The background image is in png format and the second image on top is in latex gif format. When I place the second image on top of the first image, it causes the first image to be blur.

The image looks like this when combined, (1/5 is actually an image here):

enter image description here

How to avoid the blur in the second image when I place the second image on top of the first image?


Solution

It isnt blur. Pixels on gif / 8 bits png are 100% transparent or 100% solid. So, to let the transparency softer, photoshop simulates 1-99% alpha with half tone pixels.

In a example, if you have a black image that is going to be on a white webpage (matte color), photoshop produces grey pixels to let the transparency softer. It works good in this scenario but it becomes a mess when you use this same image on a different background.

When you're at photoshop with your original transparent image, click on "save for a web", then do one of the following:

1- Save it as a png 24 bits (with transparency box checked) and it will be ok no matter the background where you'll put it on (deep transparency, no worries).

2- If you want a smaller file size and choose gif or png 8 bits, you must select a matte (color that will be at the background on your website). The result isnt perfect over multi-color/textured backgrounds; anyway, in your sample the matte is "#ca7e29".



Answered By - L777
Answer Checked By - Marilyn (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to create the smallest possible transparent png/gif of a given size in PHP?

 July 17, 2022     gif, image-processing, php, png     No comments   

Issue

I've made this code to generate the data-uri for a transparent PNG of a given size:

function createTransparentDataURI($w = 1, $h = 1) {

    // Enable output buffering
    ob_start();

    $img = imagecreatetruecolor($w, $h);
    imagesavealpha($img, true);
    $color = imagecolorallocatealpha($img, 0, 0, 0, 127);
    imagefill($img, 0, 0, $color);
    imagepng($img);
    imagedestroy($img);

    // Capture the output
    $imagedata = ob_get_contents();
    // Clear the output buffer
    ob_end_clean();

    // REF: http://stackoverflow.com/questions/9370847/php-create-image-with-imagepng-and-convert-with-base64-encode-in-a-single-file
    return 'data:image/png;base64,' . base64_encode($imagedata);
}

An example run with

echo createTransparentDataURI(1016, 312);

returns

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAA/gAAAE4CAYAAADvrFgKAAAE40lEQVR4nO3BAQ0AAADCoPdPbQ8HFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADwZltVAAEv7IggAAAAAElFTkSuQmCC

Is there any way to "compress" (PNG is lossless, but with a compression option?) this data-uri with a better encoding or using a single-color GIF? Programmatic graphics with PHP isn't my strongest area.


Solution

Considering that the image will be transparent and nothing will appear on it you don't need it to be lossless. This means you can use a color palette of single color which will create a index for this color and use the index for all pixels in the image. To create index palette PNG you should use the imagetruecolortopalette() function in your code: http://php.net/manual/en/function.imagetruecolortopalette.php

You can also set the image compression level to highest.

function createTransparentDataURI($w = 1, $h = 1) {
    //...
    //create image palette with one color, the dithering (the second argument) doesn't matter here
    imagetruecolortopalette($img, false, 1);
    imagepng($img, null, 9); //set the compression level to highest
    //...
}

This reduced the data length of image 1016x312 from 1308 to 133 bytes, which is almost by factor of ten.

By converting the binary data to base64 you can see with naked eye that there is room to compress that too:

iVBORw0KGgoAAAANSUhEUgAAA/gAAAE4AQMAAADVYspJAAAAA1BMVEUEAgSVKDOdAAAAPUlEQVR42u3BAQ0AAADCoPdPbQ8HFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/BicAAABWZX81AAAAABJRU5ErkJggg==

where the multiple "A"s are

You can enable the http's server gzip compression, to compress this response further more.

GIF wouldn't do better as it's size in my test was 910 bytes.



Answered By - Pavel Petrov
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] Why '.png' files produced by ImageMagick are so much bigger than '.jpg' & '.gif' files?

 July 17, 2022     gif, image-processing, imagemagick, jpeg, png     No comments   

Issue

I'm using ImageMagick to convert some files from one format to another. I was always under the impression that .png files were supposed to be as big/small as .jpg if not smaller, and definitely smaller than .gif.

However when I run

convert photo.jpg photo.png 

The files I'm getting out is about 6 times bigger than the original jpg.
Original jpg is a regular photo about 300x500 px, 52 kb. Output is a proper png of the same dimensions, but size is about 307 kb?

Does anyoone know what the hack is going on? Am I doing something wrong?

P.S.:

I tried both on Debian and Windows with the same results.

P.P.S.:

Also when I add resize option to this and resize to 10000 x 10000. Converting and resizing to jpg takes a few seconds, but it works, if I do the same of png, I jsut strt running out of memory altogether

P.P.P.S.: For people who keep marking this question as duplicate of PNG vs. GIF vs. JPEG vs. SVG - When best to use? . Please read carefully and understand the question. It's not a duplicate, since this question asks' about files produced programmatically with specific application (image magick). The question you marking as duplicate, is asking which image format is better to use on the web. Two DIFFERENT questions.


Solution

JPG is a lossy compression algorithm while PNG is a lossless one.

This fact alone will (in general) make JPG images smaller than PNG ones. You can tweak the compression ratios for each format, so it could also be that you're not compressing your PNG files as much as your JPG ones.

For a photographic image saving as JPG will usually produce a smaller file than PNG as there's more noise or randomness in the image for the compression to work with. Images created by graphic art tools will tend to have more hard edges and areas of solid colour which will compress better in PNG.

If you have text in your image then PNG is going to produce a better quality image as the harder edges of the characters won't be blurred like they would be if JPG is used.

GIF is smaller because it's based on an colour palette (of 256 colours) rather than the separate RGB values for each pixel (or group of pixels) in JPG and PNG.



Answered By - ChrisF
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How do I convert images from base 64 to their file types in PHP?

 July 17, 2022     bmp, gif, jpeg, php, png     No comments   

Issue

I have objects containing images as base 64 strings, the object also contains file names for the images, and file types (jpeg, png, gif & bmp) for the images. The base 64 strings have already had the tags (e.g. "data:image/png;base64" removed from the beginning.

The format for the objects ($myImg) are as follows:

  • $myImg->fileName contains the name that the converted image should be saved under.

  • $myImg->fileType describes the format that the file is supposed to be saved as - this is used to specify the path extension in the fopen() function.

  • $myImg->b64 contains the 64 bit binary string which represents the image.

The code for my function is as folows:

function toImg(ImageString $myImg){
    //Output file is in the same directory as the PHP script.
    //Uses the object's filetype attribute as the file extension.
    $outputFile = fopen($myImg->fileName . "." . $myImg->fileType, "w");
    $image = base64_decode($myImg->b64);
    fwrite($outputFile, $image);
    fclose($outputFile);
}

The function creates the image files, but I get errors when trying to view them in Xubuntu Image Viewer. The errors are as follows:

  • Error interpreting JPEG image file (Not a JPEG file: starts with 0x14 0x00)

  • Fatal error reading PNG image file: not a PNG file.

  • File does not appear to be a GIF file.

  • BMP image has bogus header data.

I've looked through and followed guides for base64 to image conversion, but none of them have encountered these errors.


Solution

Try to show the image inline in the browser, like this:

<img src="data:image/png;base64,the-base64-string" />

(change png to the correct image format)

If the image is still broken, then the image data is invalid.



Answered By - M. Eriksson
Answer Checked By - Robin (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How do I convert images from base 64 to their file types in PHP?

 July 17, 2022     bmp, gif, jpeg, php, png     No comments   

Issue

I have objects containing images as base 64 strings, the object also contains file names for the images, and file types (jpeg, png, gif & bmp) for the images. The base 64 strings have already had the tags (e.g. "data:image/png;base64" removed from the beginning.

The format for the objects ($myImg) are as follows:

  • $myImg->fileName contains the name that the converted image should be saved under.

  • $myImg->fileType describes the format that the file is supposed to be saved as - this is used to specify the path extension in the fopen() function.

  • $myImg->b64 contains the 64 bit binary string which represents the image.

The code for my function is as folows:

function toImg(ImageString $myImg){
    //Output file is in the same directory as the PHP script.
    //Uses the object's filetype attribute as the file extension.
    $outputFile = fopen($myImg->fileName . "." . $myImg->fileType, "w");
    $image = base64_decode($myImg->b64);
    fwrite($outputFile, $image);
    fclose($outputFile);
}

The function creates the image files, but I get errors when trying to view them in Xubuntu Image Viewer. The errors are as follows:

  • Error interpreting JPEG image file (Not a JPEG file: starts with 0x14 0x00)

  • Fatal error reading PNG image file: not a PNG file.

  • File does not appear to be a GIF file.

  • BMP image has bogus header data.

I've looked through and followed guides for base64 to image conversion, but none of them have encountered these errors.


Solution

Try to show the image inline in the browser, like this:

<img src="data:image/png;base64,the-base64-string" />

(change png to the correct image format)

If the image is still broken, then the image data is invalid.



Answered By - M. Eriksson
Answer Checked By - Clifford M. (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to convert multiple PNG files to an animated GIF?

 July 17, 2022     animated-gif, gif, image, java, png     No comments   

Issue

I have a java program that creates multiple PNG files (screenshots). I now need to find a way to create an animated GIF from these files and have no idea where to start.

How to convert multiple PNG files to an animated GIF?


Solution

Adapted from an old thread on Sun forums. Batteries not included, all warranties null & void.

import java.awt.image.BufferedImage;
import java.io.File;
import org.w3c.dom.Node;

import javax.imageio.*;
import javax.imageio.metadata.*;
import javax.imageio.stream.ImageOutputStream;

/**
 * Creates an animated GIF from GIF frames. A thin wrapper to code written by
 * other people, as documented on the thread on the Sun forums 'Create animated
 * GIF using imageio' http://forums.sun.com/thread.jspa?threadID=5395006 See the
 * printUsage() method for details on paramaters required.
 *
 * @author Andrew Thompson
 */
class WriteAnimatedGif {

    /**
     * See http://forums.sun.com/thread.jspa?messageID=10755673#10755673
     *
     * @author Maxideon
     * @param delayTime String Frame delay for this frame.
     */
    public static void configure(IIOMetadata meta,
            String delayTime,
            int imageIndex) {

        String metaFormat = meta.getNativeMetadataFormatName();

        if (!"javax_imageio_gif_image_1.0".equals(metaFormat)) {
            throw new IllegalArgumentException(
                    "Unfamiliar gif metadata format: " + metaFormat);
        }

        Node root = meta.getAsTree(metaFormat);

        //find the GraphicControlExtension node
        Node child = root.getFirstChild();
        while (child != null) {
            if ("GraphicControlExtension".equals(child.getNodeName())) {
                break;
            }
            child = child.getNextSibling();
        }

        IIOMetadataNode gce = (IIOMetadataNode) child;
        gce.setAttribute("userDelay", "FALSE");
        gce.setAttribute("delayTime", delayTime);

        //only the first node needs the ApplicationExtensions node
        if (imageIndex == 0) {
            IIOMetadataNode aes
                    = new IIOMetadataNode("ApplicationExtensions");
            IIOMetadataNode ae
                    = new IIOMetadataNode("ApplicationExtension");
            ae.setAttribute("applicationID", "NETSCAPE");
            ae.setAttribute("authenticationCode", "2.0");
            byte[] uo = new byte[]{
                //last two bytes is an unsigned short (little endian) that
                //indicates the the number of times to loop.
                //0 means loop forever.
                0x1, 0x0, 0x0
            };
            ae.setUserObject(uo);
            aes.appendChild(ae);
            root.appendChild(aes);
        }

        try {
            meta.setFromTree(metaFormat, root);
        } catch (IIOInvalidTreeException e) {
            //shouldn't happen
            throw new Error(e);
        }
    }

    /**
     * See http://forums.sun.com/thread.jspa?messageID=9988198
     *
     * @author GeoffTitmus
     * @param file File A File in which to store the animation.
     * @param frames BufferedImage[] Array of BufferedImages, the frames of the
     * animation.
     * @param delayTimes String[] Array of Strings, representing the frame delay
     * times.
     */
    public static void saveAnimate(
            File file,
            BufferedImage[] frames,
            String[] delayTimes) throws Exception {

        ImageWriter iw = ImageIO.getImageWritersByFormatName("gif").next();

        ImageOutputStream ios = ImageIO.createImageOutputStream(file);
        iw.setOutput(ios);
        iw.prepareWriteSequence(null);

        for (int i = 0; i < frames.length; i++) {
            BufferedImage src = frames[i];
            ImageWriteParam iwp = iw.getDefaultWriteParam();
            IIOMetadata metadata = iw.getDefaultImageMetadata(
                    new ImageTypeSpecifier(src), iwp);
            configure(metadata, delayTimes[i], i);
            IIOImage ii = new IIOImage(src, null, metadata);
            iw.writeToSequence(ii, null);
        }

        iw.endWriteSequence();

        ios.close();
    }

    /**
     * Dump the usage to the System.err stream.
     */
    public static void printUsage() {
        StringBuffer sb = new StringBuffer();
        String eol = System.getProperty("line.separator");
        sb.append("Usage: 2 forms each using 3 arguments");
        sb.append(eol);
        sb.append("1) output (animated GIF) file name");
        sb.append(eol);
        sb.append("2) input files (animation frames), separated by ','");
        sb.append(eol);
        sb.append("3) single frame rate, or comma separared list of frame rates");
        sb.append(eol);
        sb.append("java WriteAnimatedGif animate.gif frm1.gif,frm2.gif,..,frmN.gif 100");
        sb.append(eol);
        sb.append("java WriteAnimatedGif animate.gif frm1.gif,frm2.gif,..,frmN.gif 100,40,..,N");
        sb.append(eol);
        sb.append("The 2nd form must have exactly as many integers as there are frames.");
        sb.append(eol);
        sb.append("Frame rates are specified in increments of 1/100th second, NOT milliseconds.");
        sb.append(eol);

        System.err.print(sb);
    }

    /**
     * Checks that a String intended as a delayTime is an integer>0. If not,
     * dumps a warning message and the usage, then exits. If successful, returns
     * the String unaltered.
     */
    public static String checkDelay(String delay) {
        try {
            int val = Integer.parseInt(delay);
            if (val < 1) {
                System.err.println(
                        "Animation frame delay '"
                        + val
                        + "' is < 1!");
                printUsage();
                System.exit(1);
            }
        } catch (NumberFormatException nfe) {
            System.err.println(
                    "Could not parse '"
                    + delay
                    + "' as an integer.");
            printUsage();
            System.exit(1);
        }
        return delay;
    }

    /**
     * Parse the arguments and if successful, attempt to write the animated GIF.
     */
    public static void main(String[] args) throws Exception {

        if (args.length != 3) {
            printUsage();
            System.exit(1);
        }

        // deal with the output file name
        File f = new File(args[0]);

        // deal with the input file names
        String[] names = args[1].split(",");
        if (names.length < 2) {
            System.err.println("An animation requires 2 or more frames!");
            printUsage();
            System.exit(1);
        }
        BufferedImage[] frames = new BufferedImage[names.length];
        for (int ii = 0; ii < names.length; ii++) {
            frames[ii] = ImageIO.read(new File(names[ii]));
        }

        // deal with the frame rates
        String[] delays = args[2].split(",");
        // note: length of names, not delays
        String[] delayTimes = new String[names.length];
        if (delays.length != names.length) {
            System.err.println(delays.length
                    + " delays specified for "
                    + names.length
                    + " frames!");
            printUsage();
            System.exit(1);
        } else if (delays.length == 1) {
            for (int ii = 0; ii < delayTimes.length; ii++) {
                // fill all values with the single delayTime
                delayTimes[ii] = checkDelay(delays[0]);
            }
        } else {
            for (int ii = 0; ii < delayTimes.length; ii++) {
                delayTimes[ii] = checkDelay(delays[ii]);
            }
        }

        // save an animated GIF
        saveAnimate(f, frames, delayTimes);
    }
}


Answered By - Andrew Thompson
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] When to interlace an image?

 July 17, 2022     gif, image, interlacing, jpeg, png     No comments   

Issue

As a general rule of thumb when is it appropriate to make a gif interlaced, a png interlaced and a jpeg progressive?

Especially when publishing the image on the web.


Solution

  • JPEG: YES — use progressive scan. It makes files smaller (each pass gets its own Huffman table), and partial rendering looks quite good.

  • GIF: NO — it's unlikely to make the file smaller, partial rendering is poor, and it's pointless for animGIFs. It's best not to use GIF at all (yes, even for anims).

  • PNG: NO — it hurts compression (as data from each pass is statistically quite different). If the image is large, use high-quality JPEG or lossy PNG if possible, as these may load quicker than a pixelated preview of a large lossless PNG.

ImageOptim will automatically change progressive/interlaced formats when it makes files smaller.


Disclaimers for nitpickers:

  • In case of small and medium-sized images the progressive preview of each image is not going to be visible long enough for the user to appreciate it. Some browsers don't even bother rendering anything until the whole file is downloaded, so it's better to focus on saving bandwidth to get the whole page loaded ASAP.
  • Non-progressive JPEG is a bit more efficient when the files are tiny (small thumbnails), but then the savings are tiny, too.
  • iOS Safari has a higher maximum allowed image size for baseline JPEG than progressive, but the right solution there is to serve images at sizes reasonable for mobile in the first place.


Answered By - Kornel
Answer Checked By - Mary Flores (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Monday, June 27, 2022

[FIXED] Why isn't my matplotlib pie chart saving as a png image properly?

 June 27, 2022     graph, image, matplotlib, png, python     No comments   

Issue

Here is an image of my code: enter image description here

When I open my file explorer and try to view this image only a plain white image is displayed:

enter image description here

You can see that my bar chart images have saved just fine, so I'm a bit confused as to why the pie charts aren't viewable.

Anyone know what the problem might be??


Solution

You must write like this:

plt.savefig("Visualsations/plot2.png",dpi=300) 
         
plt.show()  

Save the figure first, and then use plt.show() to show it. The order matters; always check it.



Answered By - Yasin ÜNGÖREN
Answer Checked By - Terry (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home

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
All Comments
Atom
All Comments

Copyright © PHPFixing