Is there any way to have PHP detect a corrupted image?

微笑、不失礼 提交于 2019-11-28 01:11:13

问题


Is there any way to have PHP determine whether an image file is corrupted and will not be able to display properly?

I've tried to check with fopen and check whether the URL is valid, but it hasn't worked!


回答1:


Javascript solution (with involving jQuery, though this should be possible to do without it too):

<script type='text/javascript'>
    $(function(){
        var files = [
            'warning-large.png',
            'warning-large-corrupted.png',
            'http://www.example.com/none.gif',
            'http://sstatic.net/stackoverflow/img/favicon.ico'
        ];
        for ( var n in files ) {
            var img = $('<img/>');
            img.error(function(){
                alert('error:\n' + this.src);
            });
            img.load(function(){
                alert('success:\n' + this.src);
            });
            img.attr('src', files[n]);
        }
    });
</script>



回答2:


Is there any way to have PHP determine whether an image file is broken

If by broken you mean corrupted, changes are the imagecreatefrom{extension} won't be able to read them either:

if( imagecreatefromjpeg( $yourfile ) !== false ) {
    // image is okay.
}



回答3:


If you mean broken as in a 404, and not a corrupt image, you can always use something along the lines of:

if (file_exists($imageFileName)) {
  ..
}



回答4:


This works for me 100% :) I test if image exists by file_exists() and if it exists, you will catch corrupted images with this.

<img src="your_image_source" onerror="this.src='/path/to/backup/file'">



回答5:


if the files are there on your server check using file_exists function in php

http://php.net/manual/en/function.file-exists.php




回答6:


A great way to view all your latest broken files is to use cpanel "Error Log" which will show you all the last 300 broken files.



来源:https://stackoverflow.com/questions/6568247/is-there-any-way-to-have-php-detect-a-corrupted-image

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!