最新消息:20210917 已从crifan.com换到crifan.org

【已解决】Python处理图片保持分辨率不变希望降低图片文件大小

图片 crifan 590浏览 0评论
折腾:
【未解决】安卓手机Vivo的iQOO U1x的安卓游戏自动化测试速度很慢平均每次输出要10多秒
期间,去试试
用自己之前写的resize image的代码
看看:
保持分辨率不变,处理图片后,图片文件大小是否会变小
代码:
        if self.isAndroid:
            fullImgFilePath = self.driver.screenshot(fullImgFilePath)
            # optimize size
            displayInfo = self.driver.device_info["display"] # {'width': 720, 'height': 1600}
            originSize = (displayInfo["height"], displayInfo["width"])
            CommonUtils.resizeImage(fullImgFilePath, originSize, outputImageFile=fullImgFilePath)
utils/common_utils.py
    @staticmethod
    def resizeImage(inputImage,
                    newSize,
                    resample=cfgDefaultImageResample,
                    outputFormat=None,
                    outputImageFile=None
                    ):
        """
            resize input image
            resize normally means become smaller, reduce size
        :param inputImage: image file object(fp) / filename / binary bytes
        :param newSize: (width, height)
        :param resample: PIL.Image.NEAREST, PIL.Image.BILINEAR, PIL.Image.BICUBIC, or PIL.Image.LANCZOS
            https://pillow.readthedocs.io/en/stable/reference/Image.html#PIL.Image.Image.thumbnail
        :param outputFormat: PNG/JPEG/BMP/GIF/TIFF/WebP/..., more refer:
            https://pillow.readthedocs.io/en/stable/handbook/image-file-formats.html
            if input image is filename with suffix, can omit this -> will infer from filename suffix
        :param outputImageFile: output image file filename
        :return:
            input image file filename: output resized image to outputImageFile
            input image binary bytes: resized image binary bytes
        """
        openableImage = None
        if isinstance(inputImage, str):
            openableImage = inputImage
        elif CommonUtils.isFileObject(inputImage):
            openableImage = inputImage
        elif isinstance(inputImage, bytes):
            inputImageLen = len(inputImage)
            openableImage = io.BytesIO(inputImage)


        if openableImage:
            imageFile = Image.open(openableImage)
        elif isinstance(inputImage, Image.Image):
            imageFile = inputImage
        # <PIL.PngImagePlugin.PngImageFile image mode=RGBA size=3543x3543 at 0x1065F7A20>
        imageFile.thumbnail(newSize, resample)
        if outputImageFile:
            # save to file
            # imageFile.save(outputImageFile)
            CommonUtils.saveImage(imageFile, outputImageFile)
            imageFile.close()
        else:
            # save and return binary byte
            imageOutput = io.BytesIO()
            # imageFile.save(imageOutput)
            outputImageFormat = None
            if outputFormat:
                outputImageFormat = outputFormat
            elif imageFile.format:
                outputImageFormat = imageFile.format
            imageFile.save(imageOutput, outputImageFormat)
            imageFile.close()
            compressedImageBytes = imageOutput.getvalue()
            compressedImageLen = len(compressedImageBytes)
            compressRatio = float(compressedImageLen)/float(inputImageLen)
            print("%s -> %s, resize ratio: %d%%" % (inputImageLen, compressedImageLen, int(compressRatio * 100)))
            return compressedImageBytes

    @staticmethod
    def saveImage(pillowImage, outputImageFile):
        foundJpeg = re.search("\.jpe?g$", outputImageFile, re.I) # <re.Match object; span=(66, 70), match='.jpg'>
        isSaveJpeg = bool(foundJpeg) # True
        if isSaveJpeg:
            if pillowImage.mode in ("RGBA", "P"): # 'RGBA'
                # JPEG not support 'Alpha' transparency, so need convert to RGB, before save RGBA/P to jpeg
                pillowImage = pillowImage.convert("RGB")
                # <PIL.Image.Image image mode=RGB size=1600x720 at 0x107E5DAF0>
        pillowImage.save(outputImageFile)
        # 'debug/Android/app/游戏app/screenshot/20201208_142621_drawRect_154x42.jpg'
效果:
‘debug/Android/app/游戏app/screenshot/20201208_205117.jpg’
resize后,从1.4MB 变 135KB 且注意分辨率都是1600×720,并没变化
最新代码详见:
https://github.com/crifan/crifanLibPython/blob/master/crifanLib/crifanMultimedia.py
【后记】
调试遇到报错:
            # imageFile.save(outputImageFile)
            CommonUtils.saveImage(imageFile, outputImageFile)
            imageFile.close()
错误:
save file time: 0:00:00.000340
[201208 21:49:10][AppCrawler.py 90 ] unrecognized data stream contents when reading image file
    Traceback (most recent call last):
      File "/Users/xxx/dev/xxx/crawler/appAutoCrawler/AppCrawler/src/AppCrawler.py", line 84, in start
        self.set_InitialUrl()
      File "/Users/xxx/dev/xxx/crawler/appAutoCrawler/AppCrawler/src/AppCrawler.py", line 159, in set_InitialUrl
        self.doGameAutoTest()
      File "/Users/xxx/dev/xxx/crawler/appAutoCrawler/AppCrawler/src/AppCrawler.py", line 782, in doGameAutoTest
        while (curRetryNum <= intoHomePageCheckMaxRetryNum) and (not self.waitStartToHome(curRetryNum)):
      File "/Users/xxx/dev/xxx/crawler/appAutoCrawler/AppCrawler/src/AppCrawler.py", line 274, in waitStartToHome
        self.tryAutoClickAndClosePopup()
      File "/Users/xxx/dev/xxx/crawler/appAutoCrawler/AppCrawler/src/common/MainUtils.py", line 5155, in tryAutoClickAndClosePopup
        self.tryAutoClickTip()
      File "/Users/xxx/dev/xxx/crawler/appAutoCrawler/AppCrawler/src/common/MainUtils.py", line 5082, in tryAutoClickTip
        isAutoClick, matchResult, imgPath, wordsResultJson = self.isAutoClickTipPage(isRespFullInfo=True)
      File "/Users/xxx/dev/xxx/crawler/appAutoCrawler/AppCrawler/src/common/MainUtils.py", line 5066, in isAutoClickTipPage
        imgPath = self.getCurScreenshot()
      File "/Users/xxx/dev/xxx/crawler/appAutoCrawler/AppCrawler/src/common/DevicesMethods.py", line 4789, in getCurScreenshot
        CommonUtils.resizeImage(fullImgFilePath, originSize, outputImageFile=fullImgFilePath)
      File "/Users/xxx/dev/xxx/crawler/appAutoCrawler/AppCrawler/utils/common_utils.py", line 420, in resizeImage
        CommonUtils.saveImage(imageFile, outputImageFile)
      File "/Users/xxx/dev/xxx/crawler/appAutoCrawler/AppCrawler/utils/common_utils.py", line 375, in saveImage
        pillowImage = pillowImage.convert("RGB")
      File "/Users/xxx/dev/xxx/crawler/appAutoCrawler/AppCrawler/venv/lib/python3.8/site-packages/PIL/Image.py", line 873, in convert
        self.load()
      File "/Users/xxx/dev/xxx/crawler/appAutoCrawler/AppCrawler/venv/lib/python3.8/site-packages/PIL/ImageFile.py", line 270, in load
        raise_ioerror(err_code)
      File "/Users/xxx/dev/xxx/crawler/appAutoCrawler/AppCrawler/venv/lib/python3.8/site-packages/PIL/ImageFile.py", line 59, in raise_ioerror
        raise OSError(message + " when reading image file")
    OSError: unrecognized data stream contents when reading image file
需要抽空去搞清楚原因。

转载请注明:在路上 » 【已解决】Python处理图片保持分辨率不变希望降低图片文件大小

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
97 queries in 0.179 seconds, using 23.37MB memory