Resize PNG image in PHP
Asked Answered
U

5

14

I'm getting a no image display when resizing PNG however the following code works for JPEG.

list($width_orig, $height_orig) = getimagesize( $fileName );

$ratio_orig = $width_orig/$height_orig;

if ($width/$height > $ratio_orig) {
   $width = $height*$ratio_orig;
} else {
   $height = $width/$ratio_orig;
}

// Resample
$image_p = imagecreatetruecolor($width, $height);

if( $type )){
    switch( $type ){
        case 'image/jpeg':
            $image = imagecreatefromjpeg($fileName);
            imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
            imagejpeg($image_p, null, 100);
        break;

        case 'image/png':
            imagealphablending( $image_p, false );
            imagesavealpha( $image_p, true );
            $image = imagecreatefrompng( $fileName );
            imagecopyresampled( $image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
            imagepng($image_p, null, 100);
        break;
    }
}

I've put the headers in but for some reason I'm doing something wrong for png images.

Usance answered 21/2, 2011 at 10:31 Comment(1)
I don't see, where you define $type variable.Pediment
L
17

Last argument in imagepng($image_p, null, 100) should be between 0 and 9.

Lxx answered 21/2, 2011 at 10:45 Comment(2)
@lan, I'm quite sure that using imagepng() with 100 as 3rd parameter should issue a warning, something like Warning: imagepng(): gd-png error: compression level must be 0 through 9 in ... ;) Be sure to check the error log next time. If you have display_errors enabled, you might also see error by opening downloaded image file in some text-editor/viewer (e.g., "View" in text mode in Total Commander) or by removing Content-Type: image/png and Content-Disposition: attachment headers (for debugging only!), if you have them.Lxx
but how avoid the background color (back)Thoron
P
8

try this:

$image = imagecreatefrompng ( $filename );
$new_image = imagecreatetruecolor ( $width, $height ); // new wigth and height
imagealphablending($new_image , false);
imagesavealpha($new_image , true);
imagecopyresampled ( $new_image, $image, 0, 0, 0, 0, $width, $height, imagesx ( $image ), imagesy ( $image ) );
$image = $new_image;

// saving
imagealphablending($image , false);
imagesavealpha($image , true);
imagepng ( $image, $filename );
Pediment answered 21/2, 2011 at 10:41 Comment(0)
C
0

see if this works

#upload de image
public function upImagem($imagem, $dir, $res, $id, $tam){

    $arquivo = $imagem;
    $arq_nome = $arquivo['name'];
    $ext = $arquivo['type'];

    $nome=$this->RenImg($arquivo, $dir, $id, $tam);
    $imagem = $arquivo['tmp_name'];


    if($ext=='image/jpeg'){
    $img = imagecreatefromjpeg($imagem);
    }
    elseif($ext=='image/png'){
    $img = imagecreatefrompng($imagem);
    }
    elseif($ext=='image/gif'){
    $img = imagecreatefromgif($imagem);
    }


    if(($ext=='image/png') or ($ext=='image/gif')){
    list($x, $y) = getimagesize($arquivo['tmp_name']);
    }
    elseif($ext=='image/jpeg'){
    $x = imagesx($img);//original height
    $y = imagesy($img);//original width
    }

    $altura  = $res[1];
    $largura = $res[0];


    $nova  = imagecreatetruecolor($largura,$altura);
    $preto = imagecolorallocate($nova, 0, 0, 0);

    if(($ext=='image/png') or ($ext=='image/gif')){
    imagealphablending($nova , false);
    imagesavealpha($nova , true);
    }

    if($ext=='image/png'){
    imagecolortransparent ($nova, $preto);
    imagecopymerge($img, $nova, 0, 0, 0, 0, imagesx($nova), imagesy($nova), 100);
    imagecopyresized($nova,$img,0,0,0,0,$largura,$altura, $x, $y );
    }
    else {
    imagecopyresampled($nova,$img,0,0,0,0,$largura,$altura,$x,$y);
    }


    if($ext=='image/jpeg'){
    imagejpeg($nova,$nome,99);
    }

    elseif($ext=='image/gif'){
    imagealphablending($nova , false);
    imagesavealpha($nova , true);
    imagegif($nova,$nome,99);
    }

    elseif($ext=='image/png'){
    imagealphablending($nova , false);
    imagesavealpha($nova , true);
    imagepng($nova,$nome);
    }

    imagedestroy($img);
    imagedestroy($nova);

}



#renames the image
public function RenImg($arq,$dir,$id,$tam){

    $arq_nome = $arq['name'];
    $arq_nome2=str_replace('.jpg','',$arq['name']);//renomeia o arquivo
    $arq_nome2=str_replace('.png','',$arq_nome2);//renomeia o arquivo
    $arq_nome2=str_replace('.gif','',$arq_nome2);//renomeia o arquivo
    //$new_name = md5($arq_nome);
    $ext = $this->getExt($arq_nome);
    $nome = $dir.$id.$tam.'.jpg';//.'.'.$ext

    return $nome;

}


#capture the file extension
public function getExt($arq){

    $ext = pathinfo($arq, PATHINFO_EXTENSION);

    return $ext;

}
Cheddite answered 16/6, 2014 at 12:37 Comment(0)
L
0

This is a code i use for JPG/PNG rezise.

$imagename = "default";
if (isset ($_FILES['arquivo'])) {
    $imagename = $imagename . ".jpg";
    $source = $_FILES['arquivo']['tmp_name'];
    $target = "images/tmp/" . $imagename;
    $type = $_FILES["arquivo"]["type"];

//JPG or JPEG
    if ($type == "image/jpeg" || $type == "image/jpg") {
        move_uploaded_file($source, $target);
        $imagepath = $imagename;
        $save = "images/" . $imagepath; //Path to save the image
        $file = "images/tmp/" . $imagepath; //path to orginal size image
        list($width, $height) = getimagesize($file);
        $modwidth = 1920;
        $diff = $width / $modwidth; // Use $modheight = $idff to mantain aspect ratio
        $modheight = 1080;
        $tn = imagecreatetruecolor($modwidth, $modheight);
        $image = imagecreatefromjpeg($file);
        imagecopyresampled($tn, $image, 0, 0, 0, 0, $modwidth, $modheight, $width, $height);
        echo "<center><b><h5>Image was updated!</h5></b>";
        imagejpeg($tn, $save, 100);
    } elseif ($type == "image/png") { //PNG
        move_uploaded_file($source, $target);
        $imagepath = $imagename;
        $save = "images/" . $imagepath; //Path to save the image
        $file = "images/tmp/" . $imagepath; //path to orginal size image
        list($width, $height) = getimagesize($file);
        $modwidth = 1920;
        $diff = $width / $modwidth; // Use $modheight = $idff to mantain aspect ratio
        $modheight = 1080;
        $tn = imagecreatetruecolor($modwidth, $modheight);
        imagealphablending($tn, false);
        imagesavealpha($tn, true);
        $image = imagecreatefrompng($file);
        imagecopyresampled($tn, $image, 0, 0, 0, 0, $modwidth, $modheight, $width, $height);
        echo "Image was updated!";
        imagepng($tn, $save, 9);
    } else {
        echo "Error!";
    }
}
Lylelyles answered 31/12, 2021 at 15:20 Comment(0)
B
0
  function createBanner($backgroundWidth, $backgroundHeight, 
  $insideImageWidth, $insideImageHeight, $backgroundColor, 
  $insideImagePath)
{

$banner = imagecreatetruecolor($backgroundWidth, 
$backgroundHeight);

// Convert hex to RGB for the background color
list($r, $g, $b) = sscanf($backgroundColor, "#%02x%02x%02x");

// Allocate the background color (white)
$bgColor = imagecolorallocate($banner, $r, $g, $b);

// Fill the banner with the background color (white)
imagefill($banner, 0, 0, $bgColor);

// Load the inside image with transparency support
$insideImage = imagecreatefrompng($insideImagePath);

// Enable alpha blending and save full alpha channel information
imagesavealpha($insideImage, true);

imagealphablending($insideImage, false);

// Resize the inside image to fit within the specified dimensions
$resizedInsideImage = imagecreatetruecolor($insideImageWidth, 
$insideImageHeight);

// Fill the resized inside image with the background color (white)
imagefill($resizedInsideImage, 0, 0, $bgColor);

imagecopyresampled($resizedInsideImage, $insideImage, 0, 0, 0, 0, 
$insideImageWidth, $insideImageHeight, imagesx($insideImage) , 
imagesy($insideImage));

// Capture the output of the image without saving to a file
ob_start();

imagepng($resizedInsideImage);

$imageData = ob_get_contents();

ob_end_clean();

// Clean up resources
imagedestroy($banner);

imagedestroy($insideImage);

imagedestroy($resizedInsideImage);

return $imageData;
}
  $backgroundWidth     = 580;
  $backgroundHeight    = 346;
  $insideImageWidth    = 280;
  $insideImageHeight   = 280;
  $backgroundColor     = "#ffffff"; // White background
  $insideImagePath     = 
  "https://shop.mmtcpamp.com/uploads/product/gold-coin-tola-2.png"; 

  createBanner($backgroundWidth, $backgroundHeight, 
  $insideImageWidth, $insideImageHeight, $backgroundColor, 
  $insideImagePath);
  
  ## OUTPUT IMAGE

  echo '<html><head></head><body><img 
  src="data:image/png;base64,' . 
  base64_encode(createBanner($backgroundWidth, $backgroundHeight, 
  $insideImageWidth, $insideImageHeight, $backgroundColor, 
  $insideImagePath)) . '"></body></html>';
  
   ##ORGINAL IMAGE = 
  'https://shop.mmtcpamp.com/uploads/product/gold-coin-tola-2.png';

   **SUPPORT PNG IMAGE**
Bromberg answered 5/1 at 7:16 Comment(1)
Hi and welcome. Your answer only contains code. A bit of explanation, more details, would help use your answer.Mirianmirielle

© 2022 - 2024 — McMap. All rights reserved.