Загрузка прозрачных изображений добавляет черный фон - PullRequest
0 голосов
/ 05 февраля 2012

Я пытаюсь создать функцию для загрузки аватаров. Моя проблема в том, что когда я загружаю прозрачное изображение, после изменения его размера оно превращается во все, что является прозрачным черным.

Я пытался использовать опции imagesavealpha () и imagealphablending (), но фон все еще становится черным.

Может быть, я просто слепой и не вижу проблемы в коде, но я не знаю, почему это происходит.

Я могу подтвердить, что после того, как изображение было перемещено в папку image / avatars сразу после загрузки, фон остается прозрачным.

это мой текущий код, я тестировал с .png изображениями:

function upload_avatar(){
    $base_path = SYSTEM_PATH;

    if($_FILES['avatar_img']['tmp_name'] != '') {
        $id = md5($this->user_id());
        $filename = $_FILES['avatar_img']['name'];
        $file_basename = substr($filename, 0, strripos($filename, '.')); // strip extention
        $file_ext = substr($filename, strripos($filename, '.')); // strip name
        $filesize = $_FILES['avatar_img']['size'];
        $newfilename = $id . $file_ext;

        if ($file_ext == ".jpg" || $file_ext == ".JPG" || $file_ext == ".jpeg" || $file_ext == ".png" || $file_ext == ".gif"){
            if($filesize <= 153600){

                move_uploaded_file($_FILES['avatar_img']['tmp_name'], $base_path."/images/avatars/" . $newfilename);

                //resize image form
                list($width, $height) = getimagesize($base_path."/images/avatars/" . $newfilename);
                $scale_height = $height/$width;
                $scale_width = $width/$height;

                //Find height and width of the image
                if($width > $height && $width > 150){
                    $width_new = 150;
                    $height_new = round($width_new*$scale_height);
                }else if($height > $width && $height > 150){
                    $height_new = 150;
                    $width_new = round($height_new*$scale_width);
                }else{
                    $height_new = $height;
                    $width_new = $width;
                }

                switch($file_ext) {
                    case ".jpg" :
                        case ".jpeg":
                            $source = imagecreatefromjpeg($base_path."/images/avatars/" . $newfilename);
                    break;

                    case ".png" :
                        $source = imagecreatefrompng($base_path."/images/avatars/" . $newfilename);
                    break;

                    default:
                        $source = imagecreatefromgif($base_path."/images/avatars/" . $newfilename);
                    break;
                }

                $destination = imagecreatetruecolor($width_new, $height_new);

                imagesavealpha($destination, true);
                imagealphablending($destination, true);

                imagecopyresized($destination, $source, 0, 0, 0, 0, $width_new, $height_new, $width, $height);

                switch($file_ext) {
                    case ".jpg":
                    case ".jpeg":
                        imagejpeg($destination, $base_path."/images/avatars/" . $newfilename, 85);
                    break;

                    case ".png":
                        imagepng($destination, $base_path."/images/avatars/" . $newfilename, 8);
                    break;

                    default:
                        imagegif($destination, $base_path."/images/avatars/" . $newfilename, 85);
                    break;
                }

                return $newfilename;
            }else{
                $this->upload_avatar = '<br />But the avatar was not updated. The avatar\'s size exceeded the 150kb limit. ';
                return '';
            }
        }else{
            $this->upload_avatar = '<br />But the avatar was not updated. The avatar must be one of the following formats: jpg, jpeg, png or gif. ';
            return '';
        }
    }else{
        return '';
    }
}

Любая помощь будет признательна, так как я схожу с ума, глядя на это сейчас.

Спасибо!

1 Ответ

1 голос
/ 05 февраля 2012

Это здесь может быть то, что вы ищете. Второй комментарий содержит пример изменения размера PNG и GIF-файлов при сохранении прозрачности.

p.s. Я бы добавил это как комментарий, но у меня пока нет на это прав.

...