首页 > 解决方案 > 上传图片并用php调整大小后,上传的图片是黑色的

问题描述

我通常使用此代码上传图像并且它工作正常,但是几天前它开始在新服务器上给我带来问题,当加载图像特别是 jpeg 图像或来自 iphone 或 mac 的图像时,它加载的图像完全是黑色的。正确更改尺寸,但图像为黑色。

这是我用来在我多产的几个学校和个人中用 php 上传图像的代码,以前可以正常工作。所以不知道是不是因为PHP版本的变化

<?php
$exp = explode(".", $_FILES["image"]["name"]);
    if($_FILES['image']['name'] != ""){ // El campo foto contiene una imagen...
        // Primero, hay que validar que se trata de un JPG/GIF/PNG
        $allowedExts = array("jpg", "jpeg", "gif", "png", "JPG", "GIF", "PNG");
        $extension = end($exp);
        if ((($_FILES["image"]["type"] == "image/gif")
                || ($_FILES["image"]["type"] == "image/jpeg")
                || ($_FILES["image"]["type"] == "image/png")
                || ($_FILES["image"]["type"] == "image/pjpeg"))
                && in_array($extension, $allowedExts)) {
            // el archivo es un JPG/GIF/PNG, entonces...
            $extension = end($exp);
            $foto = substr(md5(uniqid(rand())),0,10).".".$extension;
            $directorio = "CLIENTES"; // directorio de tu elección
            // almacenar imagen en el servidor
            move_uploaded_file($_FILES['image']['tmp_name'], $directorio.'/'.$foto);
            $resFoto = 'res_'.$foto;
            resizeImagen($directorio.'/', $foto, 500, 500,$resFoto,$extension);
            unlink($directorio.'/'.$foto);
            $_SESSION['ERROR']="Se cargo correctamente !!!";
            $OK="1";
        } else { // El archivo no es JPG/GIF/PNG
            $OK="0";
            $_SESSION['ERROR']="No tiene un formato compatible !!!";
          }
    } else { // El campo foto NO contiene una imagen
        $OK="0";
        $_SESSION['ERROR']="No se selecciono archivo!!!";
    }


####
## Función para redimencionar las imágenes
## utilizando las liberías de GD de PHP
####

function resizeImagen($ruta, $nombre, $alto, $ancho,$nombreN,$extension){
    $rutaImagenOriginal = $ruta.$nombre;
    if($extension == 'GIF' || $extension == 'gif'){
    $img_original = imagecreatefromgif($rutaImagenOriginal);
    }
    if($extension == 'jpg' || $extension == 'JPG'){
    $img_original = imagecreatefromjpeg($rutaImagenOriginal);
    }
    if($extension == 'png' || $extension == 'PNG'){
    $img_original = imagecreatefrompng($rutaImagenOriginal);
    }
    $max_ancho = $ancho;
    $max_alto = $alto;
    list($ancho,$alto)=getimagesize($rutaImagenOriginal);
    $x_ratio = $max_ancho / $ancho;
    $y_ratio = $max_alto / $alto;
    if( ($ancho <= $max_ancho) && ($alto <= $max_alto) ){//Si ancho 
    $ancho_final = $ancho;
        $alto_final = $alto;
    } elseif (($x_ratio * $alto) < $max_alto){
        $alto_final = ceil($x_ratio * $alto);
        $ancho_final = $max_ancho;
    } else{
        $ancho_final = ceil($y_ratio * $ancho);
        $alto_final = $max_alto;
    }
    $tmp=imagecreatetruecolor($ancho_final,$alto_final);
    imagecopyresampled($tmp,$img_original,0,0,0,0,$ancho_final, $alto_final,$ancho,$alto);
    imagedestroy($img_original);
    $calidad=70;
    imagejpeg($tmp,$ruta.$nombreN,$calidad);

}

$img=$directorio;
$img.="/";
$img.=$resFoto;
?>

我唯一的错误是,加载的图像完全是黑色的。

标签: phpimageupload

解决方案


我在做这种工作时也面临同样的问题。我正在使用这个类:

class ResizeImage extends MX_Controller{
    public function __construct() {
        parent::__construct();
    }
    var $image;
    var $image_type;

    static function makeDir($path) {
        return is_dir($path) ||  mkdir($path, 0777, true);
    }

    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) {

       // do this or they'll all go to jpeg
       $image_type=$this->image_type;

       if( $image_type == IMAGETYPE_JPEG ) {
           imagejpeg($this->image,$filename,$compression);
       } elseif( $image_type == IMAGETYPE_GIF ) {
           imagegif($this->image,$filename);  
       } elseif( $image_type == IMAGETYPE_PNG ) {
           // need this for transparent png to work          
           imagealphablending($this->image, false);
           imagesavealpha($this->image,true);
           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 resize1($width,$height,$forcesize='n') {
//   /* optional. if file is smaller, do not resize. */
//     if ($forcesize == 'n') {
//       if ($width > $this->getWidth() && $height > $this->getHeight()){
//           $width = $this->getWidth();
//           $height = $this->getHeight();
//       }
//     }

//     $new_image = imagecreatetruecolor($width, $height);
//     /* Check if this image is PNG or GIF, then set if Transparent*/  
//     if(($this->image_type == IMAGETYPE_GIF) || ($this->image_type==IMAGETYPE_PNG)){
//         imagealphablending($new_image, false);
//         imagesavealpha($new_image,true);
//         $transparent = imagecolorallocatealpha($new_image, 255, 255, 255, 127);
//         imagefilledrectangle($new_image, 0, 0, $width, $height, $transparent);
//     }
//     imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight());

//     $this->image = $new_image;   
// }
function resize($width,$height,$forcesize='n') {
    $new_image = imagecreatetruecolor($width, $height);
    $transparent=imagefill($new_image, 0, 0, imagecolorallocatealpha($new_image, 255, 255, 255, 127));
    imagealphablending($new_image, false);
    imagesavealpha($new_image, true);
    imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight());
    $this->image = $new_image;
}  

}#End of ResizeImage class

所以我评论了 resize1() 函数并创建了新的 resize() 函数。请检查它是否也可以帮助您。


推荐阅读