태그 보관물: file-corruption

file-corruption

손상된 그래픽 파일 스캔 자동화 손상되었습니다. 그중 일부는 실제 파일이 아니기

누구든지 그래픽 파일 (특히 JPEG, GIF 및 PNG)이 손상되었는지 (바람직하게는 자동화 된 방식으로) 확인하는 방법을 알고 있습니까?


설명:

며칠 전에 명령이 잘못 작동하여 실제로 공간이 부족한 FAT32 볼륨에서 수천 개의 그래픽 파일을 삭제했습니다. 몇 가지 다른 파일 / 사진 복구 프로그램을 사용했지만 당연히 복구 할 수있는 용량이 제한되어 있습니다 (다행히도 볼륨에 8KB 클러스터가있어 다소 도움이됩니다).

어쨌든 조각난 큰 파일 중 일부가 손상되었습니다. 그중 일부는 실제 파일이 아니기 때문에 (복구 소프트웨어는 단순히 덮어 쓴 디렉토리 항목으로 지정된 클러스터를 덤프 했으므로) 다른 일부는 조각화로 인해 손상되었습니다.

또한 일부 그림 형식은 작은 버전의 그림을 축소판 그림으로 포함하기 때문에 실제 파일 (즉, 전체 크기로 볼 때 그림)이 손상 될 수 있지만 축소판 그림은 손상되지 않았으므로 손상되지 않을 수 있습니다.


다음은 몇 가지 예입니다.

다음은 두 번째입니다. 너무 손상되어 아무것도 표시되지 않습니다.

손상된 이미지

(세 번째 는 올바른 헤더가 없기 때문에 업로드 조차하지 않습니다!)



답변

동일한 질문에 대답하려고 하면서이 문제를 우연히 발견했기 때문에 내가 찾은 또 다른 훌륭한 솔루션을 추가 할 것입니다.

나쁜 페기

응용 프로그램의 스크린 샷

사용법
메뉴에서 File > Scan파일 대화 상자를 선택한 다음 이미지가있는 폴더를 찾습니다. 그러면 프로그램은 폴더와 모든 하위 폴더에서 이미지 (.jpg, .png, .bmp, .gif)를 스캔하기 시작합니다. 많은 사진을 스캔하려면 프로그램이 이미지 파일을 완전히로드하고 구문 분석해야하므로 밤새 실행할 수 있기 때문에 다소 시간이 걸립니다.

스캔하는 동안 상태 표시 줄에 진행률이 표시됩니다. 완벽하지 않은 이미지는 목록에 직접 표시됩니다. 목록에서 이미지를 클릭하면 이미지 모양의 미리보기가 표시됩니다. 종종 이미지는 파일 형식에 사소한 문제가 있으며 이미지는 여전히 잘 보입니다. 다른 경우에는 이미지가 전혀 렌더링되지 않고 미리보기가 검은 색이됩니다. 때로는 이미지가 손상되어 위의 스크린 샷과 같은 것을 볼 수 있습니다.

매우 유용한 트릭은 열 머리글을 클릭 Reason하면 이미지의 손상 정도에 따라 이미지가 정렬됩니다 (예 : 여전히 올바르게 렌더링되는 모든 잘못된 파일 형식이 맨 아래로 이동하여보다 심각한 경우에 집중할 수 있음) .

또한 첫 번째 스캔이 완료되고 다른 스캔을 시작한 경우 결과가 목록에 추가됩니다. 따라서 이미지가있는 다른 폴더가 많은 경우 새 스캔을 시작할 때 목록을 지우지 않고 순차적으로 스캔 할 수 있습니다. 목록을 지우려면 상황에 맞는 메뉴를 사용하고을 클릭하십시오 Clear list.

링크
Windows, Linux 및 OS X 용 다운로드는 여기 ( https://www.coderslagoon.com) 에서 찾을 수 있습니다.

소스 코드는 다음과 같습니다 :
https://github.com/llaith/BadPeggy


답변

JPEG 파일 의 jpeginfo-c‘옵션을 사용해보십시오 .

나는 당신이 보여주는 부패가 나쁜 메모리 카드로도 일어나는 것을 보았습니다.
원하는 것이 가능하고 사용 가능해야합니다 . 그래픽 파일의 손상을 확인하십시오 . 그래픽 파일 형식
의 온라인 백과 사전 섹션 .

PNG 기능대한 기본 소개의 파일 무결성 검사 도 참조하십시오 .

이 Stackoverflow 질문에 관심이있을 수 있습니다
. 이미지 (PNG, JPEG 또는 GIF)가 손상되었는지 프로그래밍 방식으로 확인하려면 어떻게해야 합니까?


갱신 : 소스 타르볼 을위한 버전 1.6.1 에 의해 티모 Kokkonen .
머신의 바이너리를 빌드 할 수 있어야합니다.


답변

ImageMagick의 식별 프로그램은 이미지가 손상되었는지 알려줍니다. 식별에서 none-0 리턴 코드에 대한 ‘for i in find’루프 테스트를 수행하면 손상되거나 손상된 파일 목록을 덤프하기 위해 테스트를 매우 쉽게 스크립팅 할 수 있습니다. PowerShell을 사용하여 Windows에서도 작동합니다.

여기에 이미지 설명을 입력하십시오

경로 변경 사항이 포함 된 다음 코드는 powershell에서 잘 작동합니다.

$stream = [System.IO.StreamWriter] "corrupt_jpegs.txt"
get-childitem "c:\" -include *.jpg -recurse | foreach ($_) {
    & "C:\Program Files\ImageMagick-6.7.1-Q16\identify.exe" $_.fullname > $null
    if($LastExitCode -ne 0){
        $stream.writeline($_.fullname)
    }
}
$stream.close()


답변

이 작업은 Python Imaging Library의 .verify()명령 을 사용하여 수행 할 수 있습니다 . [1]

Windows에서 이것을 실행하려면 Python (현재 최신 Python 2 릴리스를 설치 함)을 설치 한 다음 Pillow (PIL (Python Imaging Library) 포크) 을 설치하십시오 . 그런 다음 jpeg_corrupt.py [2] 코드를 복사하여 그 내용을 .PY 파일 (예 : jpeg_corrupt.py)에 저장하십시오.

내가 코드의 다음 줄을 변경하는 것으로 jpeg_corrupt.py :
self.globs = ['*.jpg', '*.jpe', '*.jpeg']

self.globs = ['*.jpg', '*.jpe', '*.jpeg', '*.png', '*.gif']
이 .PNG 및 .GIF 파일도 스캔 할 수 있도록.

그런 다음 Windows 명령 프롬프트 (cmd.exe)를 통해 다음과 같이 실행할 수 있습니다. C:\Python27\python.exe "C:\Directory containing the .PY file\jpeg_corrupt.py" "C:\Directory of folder to be scanned"

명령의 첫 번째 부분 인 ‘ C : \ Python27 \ python.exe ‘는 설치 한 Python 버전과 설치 한 디렉토리에 따라 다를 수 있습니다. 이 예에서는 Python 2.7의 기본 설치 디렉토리입니다.

지정된 디렉토리 및 모든 서브 디렉토리에있는 모든 JPG, GIF 및 PNG 이미지를 스캔해야합니다. 손상된 이미지 파일을 감지하면 출력이 표시됩니다.

OP의 샘플 이미지에서 이것을 실행했으며 다음과 같은 오류 메시지가 표시되었습니다 ...\YcB9n.png: string index out of range.

코드는 .BAT 스크립트 파일에도 입력 할 수 있으므로 명령 프롬프트를 사용하지 않고도 지정된 디렉토리를 쉽게 실행할 수 있습니다.

C:\Python27\python.exe "C:\Directory containing the .PY file\jpeg_corrupt.py" "%CD%"
pause


출처 :

[1] : 스택 오버플로의 답변- “이미지 (PNG, JPEG 또는 GIF)가 손상되었는지 프로그래밍 방식으로 확인하려면 어떻게합니까?” 작성자 : ChristopheD
[2] : [1]에 링크 된 SO 답변에서 Denilson Sá의 의견


답변

OP가 원하는 것을 정확하게 수행하기 위해 galacticninja의 답변에서 코드를 수정 했습니다. 동일한 방식으로 실행되지만 C:\명령 프롬프트에 이미지를 나열하는 대신 파일을 루트 디렉토리 의 catch 폴더로 이동 합니다.

Pastebin 또는 아래 에서 수정 된 코드 찾을 수 있습니다 .

#This program will scan a directory and all it's subdirectories for corrupted jpg, png, gif, and bmp images and collect them in a Catch folder

#To run this program you will need to install Python 2.7 and PILLOW
#Once installed save this file in a notepad document with the .py extension
#Than run cmd.exe and type the following: C:\Python27\python.exe "C:\Directory this is saved in\this.py" "C:\Directory to be scanned"
#You must make a folder called Catch in your root C:\ directory for the corrupted images to be collected in


#!/usr/bin/env python2
# -*- coding: utf-8 -*-
# vi:ts=4 sw=4 et

# Okay, this code is a bit ugly, with a few "anti-patterns" and "code smell".
# But it works and I don't want to refactor it *right now*.

# TODO:
#  * Refactor it a little
#  * Add support for custom filename filter (instead of the hardcoded one)

#Big thanks to denilsonsa for writing most of this code at https://bitbucket.org/denilsonsa/small_scripts/src/542edd54d290d476603e939027ca654b25487d85/jpeg_corrupt.py?at=default


import getopt
import fnmatch
import re
import os
import os.path
import sys
import PIL.Image


available_parameters = [
    ("h", "help", "Print help"),
    ("v", "verbose", "Also print clean files"),
]


class ProgramOptions(object):
    """Holds the program options, after they are parsed by parse_options()"""

    def __init__(self):
        self.globs = ['*.jpg', '*.jpe', '*.jpeg', '*.gif', '*.png', '*.bmp']
        self.glob_re = re.compile('|'.join(
            fnmatch.translate(g) for g in self.globs
        ), re.IGNORECASE)

        self.verbose = False
        self.args = []


def print_help():
    global opt
    scriptname = os.path.basename(sys.argv[0])
    print "Usage: {0} [options] files_or_directories".format(scriptname)
    print "Recursively checks for corrupt image files"
    print ""
    print "Options:"
    long_length = 2 + max(len(long) for x,long,y in available_parameters)
    for short, long, desc in available_parameters:
        if short and long:
            comma = ", "
        else:
            comma = "  "

        if short == "":
            short = "  "
        else:
            short = "-" + short[0]

        if long:
            long = "--" + long

        print "  {0}{1}{2:{3}}  {4}".format(short,comma,long,long_length, desc)

    print ""
    print "Currently (it is hardcoded), it only checks for these files:"
    print "  " + " ".join(opt.globs)


def parse_options(argv, opt):
    """argv should be sys.argv[1:]
    opt should be an instance of ProgramOptions()"""

    try:
        opts, args = getopt.getopt(
            argv,
            "".join(short for short,x,y in available_parameters),
            [long for x,long,y in available_parameters]
        )
    except getopt.GetoptError as e:
        print str(e)
        print "Use --help for usage instructions."
        sys.exit(2)

    for o,v in opts:
        if o in ("-h", "--help"):
            print_help()
            sys.exit(0)
        elif o in ("-v", "--verbose"):
            opt.verbose = True
        else:
            print "Invalid parameter: {0}".format(o)
            print "Use --help for usage instructions."
            sys.exit(2)

    opt.args = args
    if len(args) == 0:
        print "Missing filename"
        print "Use --help for usage instructions."
        sys.exit(2)


def is_corrupt(imagefile):
    """Returns None if the file is okay, returns an error string if the file is corrupt."""
    #http://stackoverflow.com/questions/1401527/how-do-i-programmatically-check-whether-an-image-png-jpeg-or-gif-is-corrupted/1401565#1401565
    try:
        im = PIL.Image.open(imagefile)
        im.verify()
    except Exception as e:
        return str(e)
    return None


def check_files(files):
    """Receives a list of files and check each one."""
    global opt
    i = 0
    for f in files:
        # Filtering JPEG, GIF, PNG, and BMP images
        i=i+1
        if opt.glob_re.match(f):
            status = is_corrupt(f)
            if opt.verbose and status is None:
                status = "Ok"
            if status:
                file = "{0}".format(f, status)
                print file
                shorthand = file.rsplit('\\', 1)
                extention =shorthand[1]
                fullFileName = "C:\Catch" + "\\" + extention
                os.rename(file, fullFileName)


def main():
    global opt
    opt = ProgramOptions()
    parse_options(sys.argv[1:], opt)

    for pathname in opt.args:
        if os.path.isfile(pathname):
            check_files([pathname])
        elif os.path.isdir(pathname):
            for dirpath, dirnames, filenames in os.walk(pathname):
                check_files(os.path.join(dirpath, f) for f in filenames)
        else:
            print "ERROR: '{0}' is neither a file or a dir.".format(pathname)


if __name__ == "__main__":
    main()


답변

imagemagick을 설치하십시오. Mac이라면 Homebrew를 사용할 수 있습니다.

brew update && brew install imagemagick

그런 다음이 작은 Python 스크립트를 사용할 수 있습니다.

import os
from subprocess import Popen, PIPE

def checkImage(fn):
    proc = Popen(['identify', '-verbose', fn], stdout=PIPE, stderr=PIPE)
    out, err = proc.communicate()
    exitcode = proc.returncode

    return exitcode, out, err

for directory, subdirectories, files in os.walk('/Your/Path/To/Files/'):
    for file in files:
        filePath = os.path.join(directory, file)
        code, output, error = checkImage(filePath)
        if code != 0 or error != '':
            print(str(code)+' '+error)
            #os.remove(filePath)

교체 /Your/Path/To/Files/하고 손상된 이미지를 삭제하려면 마지막 행의 주석을 해제.


답변

identifyImageMagick 패키지에서 사용하십시오 .

샘플 예 :

identify -verbose -regard-warnings my_file.jpg >/dev/null && echo File is OK. || echo File is corrupted.

그리고 다음 명령은 현재 폴더에서 손상된 JPEG 파일을 모두 식별합니다.

find . -name \*.jpg -exec identify -verbose -regard-warnings {} >/dev/null "+"