파일이 유효한 이미지 파일인지 확인하는 방법은 무엇입니까?
현재 PIL을 사용하고 있습니다.
from PIL import Image
try:
im=Image.open(filename)
# do stuff
except IOError:
# filename not an image file
그러나 이것은 대부분의 경우를 충분히 포함하지만 xcf, svg 및 psd와 같은 일부 이미지 파일은 감지되지 않습니다. Psd 파일에서 OverflowError 예외가 발생합니다.
어떻게 든 그들을 포함시킬 수 있습니까?
많은 경우 처음 몇 개의 문자는 다양한 파일 형식에 대한 마법의 숫자가 될 것입니다. 위의 예외 검사 외에도 이것을 확인할 수 있습니다.
방금 내장 imghdr 모듈을 찾았습니다 . 파이썬 문서에서 :
imghdr 모듈은 파일 또는 바이트 스트림에 포함 된 이미지 유형을 결정합니다.
작동 방식 :
>>> import imghdr
>>> imghdr.what('/tmp/bass')
'gif'
유사한 기능을 다시 구현하는 것보다 모듈을 사용하는 것이 훨씬 낫습니다.
Brian이 제안한 것 외에도 PIL의 확인 방법을 사용 하여 파일이 손상 되었는지 확인할 수 있습니다 .
im.verify ()
이미지 데이터를 실제로 디코딩하지 않고 파일이 손상되었는지 확인합니다. 이 메서드가 문제를 발견하면 적절한 예외가 발생합니다. 이 방법은 새로 열린 이미지에서만 작동합니다. 이미지가 이미로드 된 경우 결과는 정의되지 않습니다. 또한이 방법을 사용한 후 이미지를로드해야하는 경우 이미지 파일을 다시 열어야합니다. 속성
Linux 에서는 libmagic을 사용하여 파일 형식을 식별하는 python-magic ( http://pypi.python.org/pypi/python-magic/0.1 )을 사용할 수 있습니다.
AFAIK, libmagic은 파일을 살펴보고 비트 맵 크기, 형식 버전 등과 같은 형식보다 더 많은 정보를 알려줍니다. 따라서 "유효성"에 대한 피상적 인 테스트로 볼 수 있습니다.
"유효"의 다른 정의에 대해서는 자체 테스트를 작성해야 할 수도 있습니다.
Python 바인딩을 libmagic, python-magic 에 사용한 다음 MIME 유형을 확인할 수 있습니다. 파일이 손상되었거나 손상되지 않았는지 알려주지는 않지만 어떤 유형의 이미지인지 확인할 수 있어야합니다.
최신 정보
또한 GitHub의 Python 스크립트에서 다음 솔루션을 구현했습니다 .
또한 손상된 파일 (jpg)은 종종 '깨진'이미지가 아닌지 확인했습니다. 즉, 손상된 사진 파일이 때때로 합법적 인 사진 파일로 남아 있고 원본 이미지가 손실되거나 변경되었지만 오류없이로드 할 수 있다는 것을 확인했습니다. 그러나 파일 잘림으로 인해 항상 오류가 발생합니다.
업데이트 종료
대부분의 이미지 형식과 함께 Python Pillow (PIL) 모듈을 사용하여 파일이 유효하고 손상되지 않은 이미지 파일인지 확인할 수 있습니다.
깨진 이미지도 감지하려는 경우 @Nadia Alramli가 im.verify()
방법을 올바르게 제안 하지만 가능한 모든 이미지 결함을im.verify
감지하지는 못합니다. 예를 들어 잘린 이미지는 감지하지 못합니다 (대부분의 시청자는 종종 회색 영역으로로드 됨).
Pillow 는 이러한 유형의 결함도 감지 할 수 있지만 이미지 조작 또는 이미지 디코딩 / 리코딩을 적용하거나 검사를 트리거해야합니다. 마지막으로이 코드를 사용하는 것이 좋습니다.
try:
im = Image.load(filename)
im.verify() #I perform also verify, don't know if he sees other types o defects
im.close() #reload is necessary in my case
im = Image.load(filename)
im.transpose(PIL.Image.FLIP_LEFT_RIGHT)
im.close()
except:
#manage excetions here
In case of image defects this code will raise an exception. Please consider that im.verify is about 100 times faster than performing the image manipulation (and I think that flip is one of the cheaper transformations). With this code you are going to verify a set of images at about 10 MBytes/sec with standard Pillow or 40 MBytes/sec with Pillow-SIMD module (modern 2.5Ghz x86_64 CPU).
For the other formats psd,xcf,.. you can use Imagemagick wrapper Wand, the code is as follows:
im = wand.image.Image(filename=filename)
temp = im.flip;
im.close()
But, from my experiments Wand does not detect truncated images, I think it loads lacking parts as greyed area without prompting.
I red that Imagemagick has an external command identify that could make the job, but I have not found a way to invoke that function programmatically and I have not tested this route.
I suggest to always perform a preliminary check, check the filesize to not be zero (or very small), is a very cheap idea:
statfile = os.stat(filename)
filesize = statfile.st_size
if filesize == 0:
#manage here the 'faulty image' case
Well, I do not know about the insides of psd, but I, sure, know that, as a matter of fact, svg is not an image file per se, -- it is based on xml, so it is, essentially, a plain text file.
Additionally to the PIL
image check you can also add file name extension check like this:
filename.lower().endswith(('.png', '.jpg', '.jpeg', '.tiff', '.bmp', '.gif'))
Note that this only checks if the file name has a valid image extension, it does not actually open the image to see if it's a valid image, that's why you need to use additionally PIL
or one of the libraries suggested in the other answers.
Would checking the file extensions be acceptable or are you trying to confirm the data itself represents an image file?
If you can check the file extension a regular expression or a simple comparison could satisfy the requirement.
참고URL : https://stackoverflow.com/questions/889333/how-to-check-if-a-file-is-a-valid-image-file
'programing tip' 카테고리의 다른 글
boto를 사용하여 S3 버킷의 디렉터리에 파일을 업로드하는 방법 (0) | 2020.09.11 |
---|---|
AngularJs-경로 변경 이벤트 취소 (0) | 2020.09.11 |
세션 '앱': 오류 시작 활동 (0) | 2020.09.11 |
JQuery 문자열에 검사가 포함됨 (0) | 2020.09.11 |
Twitter 부트 스트랩 드롭 다운을 숨기는 방법 (0) | 2020.09.11 |