목차
一、出现的问题
二、问题分析以及解决方案
백엔드 개발 PHP 튜토리얼 二、问题分析以及解决方案

二、问题分析以及解决方案

Jun 13, 2016 pm 12:02 PM
gt height resize this width

【PHP缩略图类】手机照片不能生成缩略图问题以及解决方案

本文原创,谢绝转载

一、出现的问题

这几天做了手机上传照片并裁出缩略图的接口的测试,发现不管怎么,生成的缩略图都是一片漆黑。:-(

然后就把这个缩略图类单拿出来进行测试,发现只要是手机拍出来的照片都不能进行缩略图的处理。。。。


二、问题分析以及解决方案


经过群里的请教,发现问题可能是出现在文件的类型的判断上,因为png图片自带一个透明的图层,导致不能直接转换成jpg的文件,而手机排出的照片扩展名是jpg.

所以,得出的结论是手机拍出的是jpg扩展名的png图片


由于扩展名是可以随意修改的,不是很能保证文件的信息的准确性,所以我们采用了 getimagesize 函数进行文件类型的获取。


//获取真实的图片类型 list($width, $height, $type, $attr) = getimagesize($this->sur_file);    switch($type) {          case 1 :              $img_type = 'gif';              break;          case 2 :              $img_type = 'jpeg';              break;          case 3 :              $img_type = 'png';              break;          case 15 :              $img_type = 'wbmp';              break;          default :              return false;      }  
로그인 후 복사


三、生成缩略图类


下面把修改后的生成缩略图的类贴出来,供大家指正~


/** * php生成缩略图类 * 修改者 点点细雨  * 文章出处 : http://blog.csdn.net/diandianxiyu_geek * 2014-07-23 解决了图片类型不能正常识别的问题 */class thumb {    public $sur_file; //读取的原图片    public $des_file; //生成目标图片    public $tem_file; //临时图片    public $tag;  //缩略标签  0,默认,按固定的高宽生成  1,按比列或固定最大长度生成  -1,按某个宽度或某个高度缩小    public $resize_width;  //$tag为0时,目标文件宽    public $resize_height;  //$tag为0时,目标文件高    public $sca_max; //$tag为1时,1时为最大长度(高或宽之中的最大值)    public $type;  //图片类型    public $width;  //原图片宽    public $height;  //原图片高    public $size;     //原图大小    //构造函数    public function __construct($surpic, $reswid, $reshei, $despic, $mark, $scamax) {        $this->sur_file = $surpic;        $this->resize_width = $reswid;        $this->resize_height = $reshei;        $this->tag = $mark;        $this->sca_max = $scamax;        list($width, $height, $type, $attr) = getimagesize($this->sur_file);        switch ($type) {            case 1 :                $img_type = 'gif';                break;            case 2 :                $img_type = 'jpeg';                break;            case 3 :                $img_type = 'png';                break;            case 15 :                $img_type = 'wbmp';                break;            default :                return false;        }        $this->type = $img_type; //获取图片类型        $this->init_img(); //初始化图片        $this->des_file = $despic; //目标图片地址        $this->width = $width;        $this->height = $height;        $this->size = filesize($surpic);        $this->new_img();        imagedestroy($this->tem_file);    }    //图片初始化函数    private function init_img() {        if ($this->type == 'jpeg') {            $this->tem_file = imagecreatefromjpeg($this->sur_file);        } elseif ($this->type == 'jpg') {            $this->tem_file = imagecreatefromjpeg($this->sur_file);        } elseif ($this->type == 'gif') {            $this->tem_file = imagecreatefromgif($this->sur_file);        } elseif ($this->type == 'png') {            $this->tem_file = imagecreatefrompng($this->sur_file);        } elseif ($this->type == 'bmp') {            $this->tem_file = imagecreatefrombmp($this->sur_file); //bmp.php中包含        }    }    //图片生成函数    private function new_img() {        $ratio = ($this->width) / ($this->height); //原图比例        $resize_ratio = ($this->resize_width) / ($this->resize_height); //缩略后比例        $newimg = imagecreatetruecolor($this->resize_width, $this->resize_height); //生成新图片        imagealphablending($newimg, false); //这里很重要,意思是不合并颜色,直接用$img图像颜色替换,包括透明色;        imagesavealpha($newimg, true);        if ($this->tag == 0) { //按固定高宽截取缩略图            $newimg = imagecreatetruecolor($this->resize_width, $this->resize_height); //生成新图片            if ($ratio >= $resize_ratio) {//即等比例下,缩略图的高比原图长,因此高不变                imagecopyresampled($newimg, $this->tem_file, 0, 0, 0, 0, $this->resize_width, $this->resize_height, (($this->height) * $resize_ratio), $this->height);            } elseif ($ratio tem_file, 0, 0, 0, 0, $this->resize_width, $this->resize_height, $this->width, (($this->width) / $resize_ratio));            }        } elseif ($this->tag == 1) { //按固定比例或最大长度缩小            if ($this->sca_max width) * ($this->sca_max)), (($this->height) * ($this->sca_max))); //生成新图片                imagecopyresampled($newimg, $this->tem_file, 0, 0, 0, 0, (($this->width) * ($this->sca_max)), (($this->height) * ($this->sca_max)), $this->width, $this->height);            } elseif ($this->sca_max > 1) { //按某个最大长度缩小                if ($ratio >= 1) { //宽比高长                    $newimg = imagecreatetruecolor($this->sca_max, ($this->sca_max / $ratio)); //生成新图片                    imagecopyresampled($newimg, $this->tem_file, 0, 0, 0, 0, $this->sca_max, ($this->sca_max / $ratio), $this->width, $this->height);                } else {                    $newimg = imagecreatetruecolor(($this->sca_max * $ratio), $this->sca_max); //生成新图片                    imagecopyresampled($newimg, $this->tem_file, 0, 0, 0, 0, ($this->sca_max * $ratio), $this->sca_max, $this->width, $this->height);                }            }        } elseif ($this->tag == -1) { //按某个宽度或某个高度缩小            if ($resize_ratio >= 1) {//新高小于新宽,则图片按新宽度缩小                $newimg = imagecreatetruecolor($this->resize_width, ($this->resize_width / $ratio)); //生成新图片                imagecopyresampled($newimg, $this->tem_file, 0, 0, 0, 0, $this->resize_width, ($this->resize_width / $ratio), $this->width, $this->height);            } elseif ($resize_ratio resize_height * $ratio), $this->resize_height); //生成新图片                imagecopyresampled($newimg, $this->tem_file, 0, 0, 0, 0, ($this->resize_height * $ratio), $this->resize_height, $this->width, $this->height);            }        }        //输出新图片        if ($this->type == 'jpeg' || $this->type == 'jpg') {            imagejpeg($newimg, $this->des_file);        } elseif ($this->type == 'gif') {            imagegif($newimg, $this->des_file);        } elseif ($this->type == 'png') {            imagepng($newimg, $this->des_file);        } elseif ($this->type == 'bmp') {            imagebmp($newimg, $this->des_file); //bmp.php中包含        }    }#function new_img() end}
로그인 후 복사




본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

화웨이 GT3 Pro와 GT4의 차이점은 무엇입니까? 화웨이 GT3 Pro와 GT4의 차이점은 무엇입니까? Dec 29, 2023 pm 02:27 PM

많은 사용자들이 스마트 시계를 선택할 때 Huawei 브랜드를 선택하게 됩니다. 그 중 Huawei GT3pro와 GT4가 가장 인기 있는 선택입니다. 두 제품의 차이점을 궁금해하는 사용자가 많습니다. Huawei GT3pro와 GT4의 차이점은 무엇입니까? 1. 외관 GT4: 46mm와 41mm, 재질은 유리 거울 + 스테인레스 스틸 본체 + 고해상도 섬유 후면 쉘입니다. GT3pro: 46.6mm 및 42.9mm, 재질은 사파이어 유리 + 티타늄 본체/세라믹 본체 + 세라믹 백 쉘입니다. 2. 건강한 GT4: 최신 Huawei Truseen5.5+ 알고리즘을 사용하면 결과가 더 정확해집니다. GT3pro: ECG 심전도, 혈관 및 안전성 추가

수정: Windows 11에서 캡처 도구가 작동하지 않음 수정: Windows 11에서 캡처 도구가 작동하지 않음 Aug 24, 2023 am 09:48 AM

Windows 11에서 캡처 도구가 작동하지 않는 이유 문제의 근본 원인을 이해하면 올바른 솔루션을 찾는 데 도움이 될 수 있습니다. 캡처 도구가 제대로 작동하지 않는 주요 이유는 다음과 같습니다. 초점 도우미가 켜져 있습니다. 이렇게 하면 캡처 도구가 열리지 않습니다. 손상된 응용 프로그램: 캡처 도구가 실행 시 충돌하는 경우 응용 프로그램이 손상되었을 수 있습니다. 오래된 그래픽 드라이버: 호환되지 않는 드라이버가 캡처 도구를 방해할 수 있습니다. 다른 응용 프로그램의 간섭: 실행 중인 다른 응용 프로그램이 캡처 도구와 충돌할 수 있습니다. 인증서가 만료되었습니다. 업그레이드 프로세스 중 오류로 인해 이 문제가 발생할 수 있습니다. 이 문제는 대부분의 사용자에게 적합하며 특별한 기술 지식이 필요하지 않습니다. 1. Windows 및 Microsoft Store 앱 업데이트

Vue에서 이미지를 압축하고 형식을 지정하는 방법은 무엇입니까? Vue에서 이미지를 압축하고 형식을 지정하는 방법은 무엇입니까? Aug 25, 2023 pm 11:06 PM

Vue에서 이미지를 압축하고 형식을 지정하는 방법은 무엇입니까? 프런트 엔드 개발에서는 이미지를 압축하고 형식을 지정해야 하는 경우가 종종 있습니다. 특히 모바일 개발에서는 페이지 로딩 속도를 높이고 사용자 트래픽을 절약하기 위해 이미지를 압축하고 포맷하는 것이 중요합니다. Vue 프레임워크에서는 일부 도구 라이브러리를 사용하여 이미지를 압축하고 형식을 지정할 수 있습니다. 압축기.js 라이브러리를 사용한 압축 압축기.js는 이미지 압축을 위한 JavaS입니다.

html의 너비는 무엇을 의미합니까? html의 너비는 무엇을 의미합니까? Jun 03, 2021 pm 02:15 PM

HTML5에서 너비는 너비를 의미합니다. 너비 속성은 콘텐츠 영역 외부에 내부 여백, 테두리 및 외부 여백을 추가할 수 있습니다. 요소.

iPhone에서 App Store 오류에 연결할 수 없는 문제를 해결하는 방법 iPhone에서 App Store 오류에 연결할 수 없는 문제를 해결하는 방법 Jul 29, 2023 am 08:22 AM

1부: 초기 문제 해결 단계 Apple 시스템 상태 확인: 복잡한 솔루션을 살펴보기 전에 기본 사항부터 시작해 보겠습니다. 문제는 귀하의 기기에 있는 것이 아닐 수도 있습니다. Apple 서버가 다운되었을 수도 있습니다. Apple의 시스템 상태 페이지를 방문하여 AppStore가 제대로 작동하는지 확인하세요. 문제가 있는 경우 Apple이 문제를 해결하기를 기다리는 것뿐입니다. 인터넷 연결 확인: "AppStore에 연결할 수 없음" 문제는 때때로 연결 불량으로 인해 발생할 수 있으므로 인터넷 연결이 안정적인지 확인하십시오. Wi-Fi와 모바일 데이터 간을 전환하거나 네트워크 설정을 재설정해 보세요(일반 > 재설정 > 네트워크 설정 재설정 > 설정). iOS 버전을 업데이트하세요.

php提交表单通过后,弹出的对话框怎样在当前页弹出,该如何解决 php提交表单通过后,弹出的对话框怎样在当前页弹出,该如何解决 Jun 13, 2016 am 10:23 AM

php提交表单通过后,弹出的对话框怎样在当前页弹出php提交表单通过后,弹出的对话框怎样在当前页弹出而不是在空白页弹出?想实现这样的效果:而不是空白页弹出:------解决方案--------------------如果你的验证用PHP在后端,那么就用Ajax;仅供参考:HTML code

Vue2가 이를 통해 다양한 옵션의 속성에 접근할 수 있는 이유에 대해 이야기해보겠습니다. Vue2가 이를 통해 다양한 옵션의 속성에 접근할 수 있는 이유에 대해 이야기해보겠습니다. Dec 08, 2022 pm 08:22 PM

이 글은 Vue 소스 코드를 해석하는 데 도움이 될 것이며 이를 사용하여 Vue2의 다양한 옵션에서 속성에 액세스할 수 있는 이유를 소개하는 것이 모든 사람에게 도움이 되기를 바랍니다!

Python에서 이미지 크기 조정, 자르기, 회전 및 뒤집기 방법 Python에서 이미지 크기 조정, 자르기, 회전 및 뒤집기 방법 May 10, 2023 am 10:43 AM

이미지 크기 조정, 자르기, 회전 및 뒤집기 먼저 원본 이미지는 다음과 같이 인터넷에서 다운로드한 다양한 크기의 10개 이미지입니다. 작업 1: 크기 조정 이미지 크기를 PILimportImageimporttorchvision.transformsastransforms#에서 동일한 크기(320,240)로 조정합니다. 이미지에서 읽을 라이브러리 및 resizeefResizeImage():ifnotos.path.exists(rdir):os.makedirs(rdir)foriinrange(10):im=Image.open(d

See all articles