dongxing7530 2013-11-28 14:07
浏览 137
已采纳

使用php上传透明背景的png图像并保持背景透明

I have a php page which takes a user image and uploads it to my webserver.

I have just noticed that if I have a png with a transparent background, and upload it, the background is changed to white.

For example I create a new image in photoshop with a transparent background and then add a coloured circle to the page. I save the image as a png and uplod to the server via ftp then the image is shown as a circle on the webpage as the background is transparent.

If I upload the image using php with a file input box the image is changed to white.

I have tried to use imagealphablending,imagecolorallocatealpha,imagefill and imagesavealpha to retain the transparent background but it just changes the bg to black.

any clues?

heres my php code

        <?php
    $path = "../userfiles/orig/";
    $userpath="../".$_REQUEST['userpath']."/";

    function getExtension($str) {
        $i = strrpos($str,".");
        if (!$i) { return ""; } 
        $l = strlen($str) - $i;
        $ext = substr($str,$i+1,$l);
        return $ext;
    }

    $valid_formats = array("jpg", "png", "gif", "bmp","jpeg","PNG","JPG","JPEG","GIF","BMP");

    if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST"){
        $name = $_FILES['photoimg']['name'];
        $size = $_FILES['photoimg']['size'];

        if(strlen($name)){
                 $ext = getExtension($name);

                if(in_array($ext,$valid_formats)){

                    if($size<(2048*2048)){
                        $time1=time();
                        $actual_image_name =$time1."_".str_replace(" ", "_", $name);
                        $tmp = $_FILES['photoimg']['tmp_name'];

                        if(move_uploaded_file($tmp, $path.$actual_image_name)){                                     
                                     $image=$actual_image_name;                     
                                     /*--------resize image-----------*/
                                     $size = 320; // the imageheight
                                     $filedir = '../userfiles/orig/'; // the directory for the original image
                                     $thumbdir = $userpath; // the directory for the resized image
                                     $prefix = $time1.'_'; // the prefix to be added to the original name
                                     $maxfile = '20000000'; 
                                     $mode = '0666';
                                     $userfile_name =str_replace(" ", "", $_FILES['photoimg']['name']);
                                     $userfile_tmp = str_replace(" ", "", $_FILES['photoimg']['tmp_name']);
                                     $userfile_size =$_FILES['photoimg']['size'];
                                     $userfile_type = $_FILES['photoimg']['type'];

                                     if (isset($_FILES['photoimg']['name'])){
                                         $prod_img = $filedir.$actual_image_name;
                                         $prod_img_thumb = $thumbdir.$prefix.$userfile_name;
                                         move_uploaded_file($userfile_tmp, $prod_img);
                                         chmod ($prod_img, octdec($mode));
                                         $sizes = getimagesize($prod_img);
                                         $aspect_ratio = $sizes[1]/$sizes[0]; 

                                         if ($sizes[1] <= $size){
                                             $new_width = $sizes[0];
                                             $new_height = $sizes[1];
                                         }else{
                                             $new_height = $size;
                                             $new_width = abs($new_height/$aspect_ratio);
                                         }
                                         $destimg=ImageCreateTrueColor($new_width,$new_height)
                                             or die('Problem In Creating image');

                                        switch($ext){
                                            case "jpg":
                                            case "jpeg":
                                            case "JPG":
                                            case "JPEG":
                                                $srcimg=ImageCreateFromJPEG($prod_img)or die('Problem In opening Source Image');
                                            break;
                                            case "PNG":
                                            case "png":
                                                $srcimg = imageCreateFromPng($prod_img)or die('Problem In opening Source Image');
                                                imagealphablending($destimg, false);
                                                $colorTransparent = imagecolorallocatealpha($destimg, 0, 0, 0x7fff0000);
                                                imagefill($destimg, 0, 0, $colorTransparent);                                                   
                                                imagesavealpha($destimg, true);

                                            break;
                                            case "BMP":
                                            case "bmp":
                                                $srcimg = imageCreateFromBmp($prod_img)or die('Problem In opening Source Image');
                                            break;
                                            case "GIF":
                                            case "gif":
                                                $srcimg = imageCreateFromGif($prod_img)or die('Problem In opening Source Image');
                                            break;
                                            default:
                                                $srcimg=ImageCreateFromJPEG($prod_img)or die('Problem In opening Source Image');
                                        }

                                        if(function_exists('imagecopyresampled')){
                                             imagecopyresampled($destimg,$srcimg,0,0,0,0,$new_width,$new_height,imagesX($srcimg),imagesY($srcimg))
                                             or die('Problem In resizing');
                                         }else{
                                             Imagecopyresized($destimg,$srcimg,0,0,0,0,$new_width,$new_height,imagesX($srcimg),imagesY($srcimg))
                                             or die('Problem In resizing');
                                         }
                                         ImageJPEG($destimg,$prod_img_thumb,90)
                                             or die('Problem In saving');

                                     }
                                unlink($prod_img);
                                echo "<img src='".$prod_img_thumb."'>";
                            }else{
                            echo "Fail upload folder with read access.";
                            }
                    }else{
                    echo "Image file size max 3 MB";
                    }

                }else{
                    echo "Invalid file format..";
                }
            }else{
            echo "Please select image..!";
            }

        exit;
    }
    ?>
  • 写回答

1条回答 默认 最新

  • dsgd4654674 2013-11-28 14:33
    关注
    <?php
    $path = "../userfiles/orig/";
    $userpath="../".$_REQUEST['userpath']."/";
    
    function getExtension($str) {
      $i = strrpos($str,".");
      if (!$i) { return ""; }
      $l = strlen($str) - $i;
      $ext = substr($str,$i+1,$l);
      return $ext;
    }
    
    $valid_formats = array("jpg", "png", "gif", "bmp","jpeg","PNG","JPG","JPEG","GIF","BMP");
    
    if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST"){
      $name = $_FILES['photoimg']['name'];
      $size = $_FILES['photoimg']['size'];
    
      if(strlen($name)){
        $ext = getExtension($name);
    
        if(in_array($ext,$valid_formats)){
    
          if($size<(2048*2048)){
            $time1=time();
            $actual_image_name =$time1."_".str_replace(" ", "_", $name);
            $tmp = $_FILES['photoimg']['tmp_name'];
    
            if(move_uploaded_file($tmp, $path.$actual_image_name)){
              $image=$actual_image_name;
              /*--------resize image-----------*/
              $size = 320; // the imageheight
              $filedir = '../userfiles/orig/'; // the directory for the original image
              $thumbdir = $userpath; // the directory for the resized image
              $prefix = $time1.'_'; // the prefix to be added to the original name
              $maxfile = '20000000';
              $mode = '0666';
              $userfile_name =str_replace(" ", "", $_FILES['photoimg']['name']);
              $userfile_tmp = str_replace(" ", "", $_FILES['photoimg']['tmp_name']);
              $userfile_size =$_FILES['photoimg']['size'];
              $userfile_type = $_FILES['photoimg']['type'];
    
              if (isset($_FILES['photoimg']['name'])){
                $prod_img = $filedir.$actual_image_name;
                $prod_img_thumb = $thumbdir.$prefix.$userfile_name;
                move_uploaded_file($userfile_tmp, $prod_img);
                chmod ($prod_img, octdec($mode));
                $sizes = getimagesize($prod_img);
                $aspect_ratio = $sizes[1]/$sizes[0];
    
                if ($sizes[1] <= $size){
                  $new_width = $sizes[0];
                  $new_height = $sizes[1];
                }else{
                  $new_height = $size;
                  $new_width = abs($new_height/$aspect_ratio);
                }
                $destimg=ImageCreateTrueColor($new_width,$new_height)
                or die('Problem In Creating image');
    
                switch($ext){
                  case "jpg":
                  case "jpeg":
                  case "JPG":
                  case "JPEG":
                    $srcimg=ImageCreateFromJPEG($prod_img)or die('Problem In opening Source Image');
                    break;
                  case "PNG":
                  case "png":
                    $srcimg = imageCreateFromPng($prod_img)or die('Problem In opening Source Image');
                    imagealphablending($destimg, false);
                    $colorTransparent = imagecolorallocatealpha($destimg, 0, 0, 0, 0x7fff0000);
                    imagefill($destimg, 0, 0, $colorTransparent);
                    imagesavealpha($destimg, true);
    
                    break;
                  case "BMP":
                  case "bmp":
                    $srcimg = imageCreateFromBmp($prod_img)or die('Problem In opening Source Image');
                    break;
                  case "GIF":
                  case "gif":
                    $srcimg = imageCreateFromGif($prod_img)or die('Problem In opening Source Image');
                    break;
                  default:
                    $srcimg=ImageCreateFromJPEG($prod_img)or die('Problem In opening Source Image');
                }
    
                if(function_exists('imagecopyresampled')){
                  imagecopyresampled($destimg,$srcimg,0,0,0,0,$new_width,$new_height,imagesX($srcimg),imagesY($srcimg))
                  or die('Problem In resizing');
                }else{
                  Imagecopyresized($destimg,$srcimg,0,0,0,0,$new_width,$new_height,imagesX($srcimg),imagesY($srcimg))
                  or die('Problem In resizing');
                }
    
    
    
                // Saving an image
                switch(strtolower($ext)){
                  case "jpg":
                  case "jpeg":
                    ImageJPEG($destimg,$prod_img_thumb,90) or die('Problem In saving');
                    break;
    
                  case "png":
                    imagepng($destimg,$prod_img_thumb) or die('Problem In saving');
                    break;
    
                  case "bmp":
                    imagewbmp($destimg, $prod_img_thumb)or die('Problem In saving');
                    break;
    
                  case "gif":
                    imagegif($destimg,$prod_img_thumb) or die('Problem In saving');
                    break;
    
                  default:
                    // if image format is unknown, and you whant save it as jpeg, maybe you should change file extension
                    imagejpeg($destimg,$prod_img_thumb,90) or die('Problem In saving');
                }
    
    
    
              }
              unlink($prod_img);
              echo "<img src='".$prod_img_thumb."'>";
            }else{
              echo "Fail upload folder with read access.";
            }
          }else{
            echo "Image file size max 3 MB";
          }
    
        }else{
          echo "Invalid file format..";
        }
      }else{
        echo "Please select image..!";
      }
    
      exit;
    }
    ?>
    

    Sorry for my english. Problem is it that you trying to save image using imagejpeg, which means new image can't use transparent color anymore. If source image was PNG, you should save it using imagepng.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。