Jump to content

Recommended Posts

Hey guys i am currently working on a thumbnail script. The idea is to be able to resize any image on the fly by adding some parameters to the images url ex: thisimage.jpg~160x160 It's then picked up by an htaccess rule that sends it to a php script that resize the image and returns it using the GD library. The script is working great but got a problem keeping the transparency with PNG images ... What ever i do the resized image has a black background. I tryed all sorts of things but it's just not working ... can anybody help me understand where i got it wrong?

 

// [......]

        // Create output image
        $outImg = imagecreate ($outWidth, $outHeight);
        
        // Load src image
        switch($srcType) {
            case "png":
                $srcImg = imagecreatefrompng($uri);
                $background = imagecolorallocate($srcImg, 255, 255, 255);
                imagecolortransparent($srcImg, $background);
                imagealphablending($srcImg, true);
                imagesavealpha($srcImg, true);
                break;
            case "gif":
                $srcImg = imagecreatefromgif($uri);
                break;
            case "jpeg":
                $srcImg = imagecreatefromjpeg($uri);
                break;
            default: 
                diewith("unsupported file type '$uri'");
        };

        // Resize image
        imagecopyresampled($outImg, $srcImg, 0, 0, 0, 0, $outWidth, $outHeight, $srcWidth, $srcHeight);

// [......]

Link to comment
https://forums.phpfreaks.com/topic/236572-png-transparency/
Share on other sites

Bumb ... anybody?

 

i tryed this and it's still not working ...

Full script looks like

<?php
    
    // Constants
    $CACHE_DIR = "media/original";

    function diewith($msg) {
        header("HTTP/1.0 500 Internal error.");
        echo $msg;
        die;
    }

    // Get params
    $uri = $_REQUEST['uri'] or diewith("missing 'uri' argument.");
    $inWidth = $_REQUEST['w'];
    $inHeight = $_REQUEST['h'];
    $method=$_REQUEST['method'];
    
    // Handle client cache (304)
    $srcTime = @filemtime($uri) or diewith("Unable to open 'uri'");
    $reqTimeStr = isset($_SERVER['HTTP_IF_MODIFIED_SINCE']);

    // Browser cache version not too old ?
    if ((! empty($reqTimeStr)) and ($srcTime <= strtotime($reqTimeStr))) {
        // End the request with status 304
        header("HTTP/1.1 304 Not modified");
        exit;
    } else {
        // Set the last change in HTTP reponse
        header("Last-Modified: " . date('r', $srcTime));
    }

    // Get actual size of source image
    $imgInfo = getimagesize($uri) or diewith("Unable to open '$uri'");
    $srcWidth =  $imgInfo[0];
    $srcHeight = $imgInfo[1];
    $srcType   = $imgInfo[2];
    switch($srcType) { 
        case 1 : $srcType = "gif"; break;
        case 2 : $srcType = "jpeg"; break;
        case 3 : $srcType = "png"; break;
        default: $srcType = "???";
    } 
    
    // Compute the size wanted 
    if ($method == "stretch") {
    
        // Exact size
        $outWidth  = $inWidth;
        $outHeight = $inHeight;
    
    } else { /* Default : 'fit' */
       
        // Max size : resize
        $xRatio = ($inWidth) ?  ($srcWidth  / $inWidth) : 0;
        $yRatio = ($inHeight) ? ($srcHeight / $inHeight): 0;
        $ratio = max($xRatio, $yRatio, 1);
        $outWidth = intval($srcWidth / $ratio);
        $outHeight = intval($srcHeight/ $ratio);
        
    }
    
    // Compute name of cache image
    $cacheName = md5($uri).'-'.basename($uri).'#'.$outWidth.'x'.$outHeight;
    $cacheFile = dirname(__FILE__) . '/'. $CACHE_DIR . '/' . $cacheName;
  
    // If cache doesn't exist or too old, build it.
    if (!file_exists($cacheFile) or ($srcTime > filectime($cacheFile))) {
        
    if ($imgInfo[0]<$outWidth){$outWidth=$imgInfo[0];}
    if ($imgInfo[1]<$outHeight){$outHeight=$imgInfo[1];}
        
        // Create output image
        $outImg = imagecreatetruecolor ($outWidth, $outHeight);
        
        // Load src image
        switch($srcType) {
            case "png":
                $srcImg = imagecreatefrompng($uri);
                imagealphablending($srcImg, false);
                $color = imagecolorallocatealpha($srcImg, 0, 0, 0, 127); 
                imagefill($srcImg, 0, 0, $color); 
                imagesavealpha($srcImg, true); 
                break;
            case "gif":
                $srcImg = imagecreatefromgif($uri);
                break;
            case "jpeg":
                $srcImg = imagecreatefromjpeg($uri);
                break;
            default: 
                diewith("unsupported file type '$uri'");
        };

        // Resize image
        imagecopyresampled($outImg, $srcImg, 0, 0, 0, 0, $outWidth, $outHeight, $srcWidth, $srcHeight);
      
        // Save to cached thumb
        switch($srcType) {
            case "png":
                $res = imagepng($outImg, $cacheFile);
                break;
            case "gif":
                $res = imagegif($outImg, $cacheFile);
                break;
            case "jpeg":
                $res = imagejpeg($outImg, $cacheFile);
                break;
            default: 
                diewith("unsupported file type '$uri'");
        }

        // Check result 
        if (!$res) diewith("Unable to save thumb to '$cacheFile'. Check the access right of the HTTP server.");
    }

    // HTTP Header
    header("Content-Type:image/$srcType");
   
    // Dump cache file
    readfile($cacheFile) or diewith("Unable to open cached thumb '$cacheFile'");
?>

 

You can see it in action here:

http://youproud.com/new/thumbs.php?uri=media/original/47002-amour.png&w=19&h=&method=fit

 

Or Here using the htaccess redirection

http://youproud.com/new/media/original/47002-amour.png~19

 

original image here

http://youproud.com/new/media/original/47002-amour.png

 

As you can see the original image has transparancy

Link to comment
https://forums.phpfreaks.com/topic/236572-png-transparency/#findComment-1216180
Share on other sites

I think i got some if it mixed up a bit ... but it's still not working ... any help would be apreciated

 

This version should have some of the error solved but the background is still black

<?php
    
    // Constants
    $CACHE_DIR = "media/original";

    function diewith($msg) {
        header("HTTP/1.0 500 Internal error.");
        echo $msg;
        die;
    }

    // Get params
    $uri = $_REQUEST['uri'] or diewith("missing 'uri' argument.");
    $inWidth = $_REQUEST['w'];
    $inHeight = $_REQUEST['h'];
    $method=$_REQUEST['method'];
    
    // Handle client cache (304)
    $srcTime = @filemtime($uri) or diewith("Unable to open 'uri'");
    $reqTimeStr = isset($_SERVER['HTTP_IF_MODIFIED_SINCE']);

    // Browser cache version not too old ?
    if ((! empty($reqTimeStr)) and ($srcTime <= strtotime($reqTimeStr))) {
        // End the request with status 304
        header("HTTP/1.1 304 Not modified");
        exit;
    } else {
        // Set the last change in HTTP reponse
        header("Last-Modified: " . date('r', $srcTime));
    }

    // Get actual size of source image
    $imgInfo = getimagesize($uri) or diewith("Unable to open '$uri'");
    $srcWidth =  $imgInfo[0];
    $srcHeight = $imgInfo[1];
    $srcType   = $imgInfo[2];
    switch($srcType) { 
        case 1 : $srcType = "gif"; break;
        case 2 : $srcType = "jpeg"; break;
        case 3 : $srcType = "png"; break;
        default: $srcType = "???";
    } 
    
    // Compute the size wanted 
    if ($method == "stretch") {
    
        // Exact size
        $outWidth  = $inWidth;
        $outHeight = $inHeight;
    
    } else { /* Default : 'fit' */
       
        // Max size : resize
        $xRatio = ($inWidth) ?  ($srcWidth  / $inWidth) : 0;
        $yRatio = ($inHeight) ? ($srcHeight / $inHeight): 0;
        $ratio = max($xRatio, $yRatio, 1);
        $outWidth = intval($srcWidth / $ratio);
        $outHeight = intval($srcHeight/ $ratio);
        
    }
    
    // Compute name of cache image
    $cacheName = md5($uri).'-'.basename($uri).'#'.$outWidth.'x'.$outHeight;
    $cacheFile = dirname(__FILE__) . '/'. $CACHE_DIR . '/' . $cacheName;
  
    // If cache doesn't exist or too old, build it.
    if (!file_exists($cacheFile) or ($srcTime > filectime($cacheFile))) {
        
    if ($imgInfo[0]<$outWidth){$outWidth=$imgInfo[0];}
    if ($imgInfo[1]<$outHeight){$outHeight=$imgInfo[1];}
        
        // Create output image
        $outImg = imagecreatetruecolor ($outWidth, $outHeight);
        
        // Load src image
        switch($srcType) {
            case "png":
                $srcImg = imagecreatefrompng($uri);
                break;
            case "gif":
                $srcImg = imagecreatefromgif($uri);
                break;
            case "jpeg":
                $srcImg = imagecreatefromjpeg($uri);
                break;
            default: 
                diewith("unsupported file type '$uri'");
        };

        imagealphablending($outImg, false);
        $color = imagecolorallocatealpha($outImg, 0, 0, 0, 127); 
        imagefill($outImg, 0, 0, $color); 
        imagesavealpha($outImg, true); 

        // Resize image
        imagecopyresampled($outImg, $srcImg, 0, 0, 0, 0, $outWidth, $outHeight, $srcWidth, $srcHeight);
      
        // Save to cached thumb
        switch($srcType) {
            case "png":
                $res = imagepng($outImg, $cacheFile);
                break;
            case "gif":
                $res = imagegif($outImg, $cacheFile);
                break;
            case "jpeg":
                $res = imagejpeg($outImg, $cacheFile);
                break;
            default: 
                diewith("unsupported file type '$uri'");
        }

        // Check result 
        if (!$res) diewith("Unable to save thumb to '$cacheFile'. Check the access right of the HTTP server.");
    }

    // HTTP Header
    header("Content-Type:image/$srcType");
   
    // Dump cache file
    readfile($cacheFile) or diewith("Unable to open cached thumb '$cacheFile'");
?>

Link to comment
https://forums.phpfreaks.com/topic/236572-png-transparency/#findComment-1216187
Share on other sites

tryed this

 

<?php
        imagealphablending($outImg, false);
        $color = imagecolortransparent($outImg, imagecolorallocatealpha($outImg, 0, 0, 0, 127));
        imagefill($outImg, 0, 0, $color);
        imagesavealpha($outImg, true);
        
    // Resize image
        imagecopyresampled($outImg, $srcImg, 0, 0, 0, 0, $outWidth, $outHeight, $srcWidth, $srcHeight);
?>

 

Not working ...

 

Tryed this:

 

<?php
        imagecolortransparent($outImg, imagecolorallocate($outImg, 0, 0, 0));
        imagealphablending($outImg, false);
        imagesavealpha($outImg, true);
        
    // Resize image
        imagecopyresampled($outImg, $srcImg, 0, 0, 0, 0, $outWidth, $outHeight, $srcWidth, $srcHeight);
?>

 

still not working ...

Link to comment
https://forums.phpfreaks.com/topic/236572-png-transparency/#findComment-1216192
Share on other sites

tried this one as well ... same result ... wtf am i doing wrong the stupid image has transparancy but looses it when it's resized ...

 

<?php
          imageAntiAlias($outImg,true);
          imagealphablending($outImg, false);
          imagesavealpha($outImg,true);
          $transparent = imagecolorallocatealpha($outImg, 255, 255, 255, 0);
          for($x=0;$x<$outWidth;$x++) {
            for($y=0;$y<$outHeight;$y++) {
              imageSetPixel( $outImg, $x, $y, $transparent );
            }
          }
        
        // Resize image
        imagecopyresampled($outImg, $srcImg, 0, 0, 0, 0, $outWidth, $outHeight, $srcWidth, $srcHeight);
?>

Link to comment
https://forums.phpfreaks.com/topic/236572-png-transparency/#findComment-1216199
Share on other sites

I am pretty confident this one should work ... but it's not. I took it from an other script

 

<?php
        $outImg = imagecreatetruecolor ($outWidth, $outHeight);
        
        // Load src image
        switch($srcType) {
            case "png":
                $srcImg = imagecreatefrompng($uri);
                $blending = false;
                break;
            case "gif":
                $srcImg = imagecreatefromgif($uri);
                $blending = true;
                break;
            case "jpeg":
                $srcImg = imagecreatefromjpeg($uri);
                break;
            default: 
                diewith("unsupported file type '$uri'");
        };
        
        // preserve transparency for PNG and GIF images
        if ($srcType == 'png' || $srcType == 'gif'){
            // allocate a color for thumbnail
            $background = imagecolorallocate($outImg, 0, 0, 0);
            // define a color as transparent
            imagecolortransparent($outImg, $background);
            // set the blending mode for thumbnail
            imagealphablending($outImg, $blending);
            // set the flag to save alpha channel
            imagesavealpha($outImg, true);
        }  
        
        // Resize image
        imagecopyresampled($outImg, $srcImg, 0, 0, 0, 0, $outWidth, $outHeight, $srcWidth, $srcHeight);
?>

Link to comment
https://forums.phpfreaks.com/topic/236572-png-transparency/#findComment-1216204
Share on other sites

This is a working script I use, the png transparency works here, pay attention to the order

 

<?php
// Process new image
if ($_FILES['logo']['tmp_name']&&$_FILES['logo']['tmp_name']!="") {  
// set memory limit for image
ini_set("memory_limit","32M");
// Check file extension
$checkfile=$_FILES['logo']['name'];
$ext=substr($checkfile, -3);
// Redirect if not correct image type
if (!in_array($ext, array('jpg', 'JPG', 'png', 'PNG'))) {
	header("Location: redirect to some page if wrong file type");
// Close database connection
	mysql_close($link);
	exit ();
}
// Create new image (300px wide can modify to suit height if that is preferred or set both but not advised)
$file=$_FILES['logo']['tmp_name'];
list($width, $height)=getimagesize($file);
// Scale to width
	$main_width=300;
	$main_height=$height*($main_width/$width);

if ($ext=="jpg"||$ext=="JPG") {
	$image=imagecreatefromjpeg($file);
	$newname="image".time().".jpg"; // using time as part of the name guarantees a unique name for each new image to prevent duplicate naming
}
if ($ext=="png"||$ext=="PNG") {
	$image=imagecreatefrompng($file);
	$newname="image".time().".png";
}
// Create main image file
$main_image=imagecreatetruecolor($main_width, $main_height);
imagecopyresampled($main_image, $image, 0, 0, 0, 0, $main_width, $main_height, $width, $height);
$site_file="another/path/".$newname;
if ($ext=="jpg"||$ext=="JPG") {
	imagejpeg($main_image, $site_file, 100); // 100 here is the max quality setting for jpeg

}
if ($ext=="png"||$ext=="PNG") {
// Turn off alpha blending and set alpha flag
	imagepng($main_image, $site_file, 9); // 9 here is the max setting for png quality

}
?>

Link to comment
https://forums.phpfreaks.com/topic/236572-png-transparency/#findComment-1216211
Share on other sites

simple_img.class.php

<?php
class SimpleImage {
   
   var $image;
   var $image_type;

   function load($filename) {
      $image_info = getimagesize($filename);
      $this->image_type = $image_info[2];
      if( $this->image_type == IMAGETYPE_JPEG ) {
         $this->image = imagecreatefromjpeg($filename);
      } elseif( $this->image_type == IMAGETYPE_GIF ) {
         $this->image = imagecreatefromgif($filename);
      } elseif( $this->image_type == IMAGETYPE_PNG ) {
         $this->image = imagecreatefrompng($filename);
      }
   }
   function save($filename, $image_type=IMAGETYPE_JPEG, $compression=75, $permissions=null) {
      if( $image_type == IMAGETYPE_JPEG ) {
         imagejpeg($this->image,$filename,$compression);
      } elseif( $image_type == IMAGETYPE_GIF ) {
         imagegif($this->image,$filename);         
      } elseif( $image_type == IMAGETYPE_PNG ) {
         imagepng($this->image,$filename);
      }   
      if( $permissions != null) {
         chmod($filename,$permissions);
      }
   }
   function output($image_type=IMAGETYPE_JPEG) {
      if( $image_type == IMAGETYPE_JPEG ) {
         imagejpeg($this->image);
      } elseif( $image_type == IMAGETYPE_GIF ) {
         imagegif($this->image);         
      } elseif( $image_type == IMAGETYPE_PNG ) {
         imagepng($this->image);
      }   
   }
   function getWidth() {
      return imagesx($this->image);
   }
   function getHeight() {
      return imagesy($this->image);
   }
   function resizeToHeight($height) {
      $ratio = $height / $this->getHeight();
      $width = $this->getWidth() * $ratio;
      $this->resize($width,$height);
   }
   function resizeToWidth($width) {
      $ratio = $width / $this->getWidth();
      $height = $this->getheight() * $ratio;
      $this->resize($width,$height);
   }
   function scale($scale) {
      $width = $this->getWidth() * $scale/100;
      $height = $this->getheight() * $scale/100; 
      $this->resize($width,$height);
   }
   function resize($width,$height) {
      $new_image = imagecreatetruecolor($width, $height);
      imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight());
      imagefilter($new_image, IMG_FILTER_CONTRAST, -10);
      $this->image = $new_image;   
   }      
}
?>

 

 

include('simple_img.class.php');

$image = new SimpleImage();
$image->load("img.png");
$image->resize(100,100);
$image->save("img2.png");

 

Link to comment
https://forums.phpfreaks.com/topic/236572-png-transparency/#findComment-1216223
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.