def resize8(srcFile="", destFile="", w=200, h=200):
        img = Image(srcFile)

        #.def("extent", (void (Magick::Image::*)(const Magick::Geometry&, const Magick::Color&, const Magick::GravityType))&Magick::Image::extent)
        #白色背景图
        backImg = None

        #sw源图宽度
        sw = img.columns()
        #sh源图高度
        sh = img.rows()
        #若目标图的宽或高都比源图大则不处理
        if (sw <= w and sh <= h):
            backImg = Image(Geometry(w, h), 'white')
            backImg.composite(img, GravityType.CenterGravity,
                              co.OverCompositeOp)
            backImg.profile("*", Blob())
            backImg.write(destFile)
            return "True"
        #目标的宽或高都比源图的小则进行裁剪
        elif (sw > w and sh > h):
            #源图的宽高比
            sratio = float(sw) / float(sh)
            rratio = float(w) / float(h)
            #若源图宽高比大于目标图的宽高比的话,则就高缩放,从0,0位置裁前源图宽
            #print sratio,rratio
            if (sratio > rratio):
                hscale = float(h) / float(sh)
                rw = int(sw * hscale)
                rh = int(sh * hscale)
            else:
                wscale = float(w) / float(sw)
                rw = int(sw * wscale)
                rh = int(sh * wscale)

            linePos = int((rw - w) / 2)
            colPos = int((rh - h) / 2)

            img.scale("%dx%d" % (rw, rh))
            img.crop(Geometry(w, h, linePos, colPos))
            img.profile("*", Blob())
            img.write(destFile)
            return "True"
        elif (sw > w):
            backImg = Image(Geometry(w, h), 'white')
            img.crop(Geometry(w, sh, int((sw - w) / 2)))
            backImg.composite(img, GravityType.CenterGravity,
                              co.OverCompositeOp)
            backImg.profile("*", Blob())
            backImg.write(destFile)
            return "True"
        elif (sh > h):
            backImg = Image(Geometry(w, h), 'white')
            img.crop(Geometry(sw, h, 0, int((sh - h) / 2)))
            backImg.composite(img, GravityType.CenterGravity,
                              co.OverCompositeOp)
            backImg.profile("*", Blob())
            backImg.write(destFile)
            return "True"
        return "True"
Example #2
0
def create_thumb(pvi_img_path):
    img = Image(Blob(open(pvi_img_path).read()))
    img.scale(ws.thumb_size_x + 'x' + ws.thumb_size_y)
    img.quality(ws.thumb_jpeg_compression_quality)
    img.write(ws.working_directory + "tmp_thumb_resized.jpg")
    blob = Blob(open(ws.working_directory + "tmp_thumb_resized.jpg").read())
    return blob.data
Example #3
0
def get_jpg_image_data(im, quality=90):
    # quality
    im.profile("*", Blob())  # 清掉exif信息
    im.quality(quality)
    f = Blob()
    im.write(f, 'jpg')
    return getattr(f, 'data')
Example #4
0
    def get_image(self, source):
        blob = Blob()
        blob.update(source.read())
        image = Image(blob)
        orientation = image.orientation()

        if orientation in (OrientationType.UndefinedOrientation,
            OrientationType.TopLeftOrientation):
            pass
        elif orientation == OrientationType.TopRightOrientation:
            image.flop()
        elif orientation == OrientationType.BottomRightOrientation:
            image.rotate(180.)
        elif orientation == OrientationType.BottomLeftOrientation:
            image.flip()
        elif orientation == OrientationType.LeftTopOrientation:
            image.rotate(90.).flip()
        elif orientation == OrientationType.RightTopOrientation:
            image.rotate(90.)
        elif orientation == OrientationType.RightBottomOrientation:
            image.rotate(90.).flop()
        elif orientation == OrientationType.LeftBottomOrientation:
            image.rotate(270.)

        image.orientation(OrientationType.TopLeftOrientation)

        return image
 def get_image(self, source):
     try:
         blob = Blob()
         blob.update(source.read())
         img = Image(blob)
     except IOError:
         img = self._missing_image(source)
     return img
 def get_image(self, source):
     blob = Blob()
     blob.update(source.read())
     if source.name.lower().endswith('.gif'):
         image = ImageList()
         image.readImages(blob)
         image.coalesceImags()
     else:
         image = Image(blob)
     return image
 def resize2(srcFile="", destFile="", w=200, h=200):
     blobData = Blob(open(srcFile).read())
     if (h != -1):
         img = Image(blobData, Geometry(w, h))
         img.scale("%dx%d!" % (w, h))
     else:
         img = Image(blobData)
         img.scale("%dx!" % w)
     img.profile("*", Blob())
     img.write(destFile)
     return "True"
    def resize7(srcFile="", destFile="", w=200, h=200):
        img = Image(srcFile)

        #白色背景图
        backImg = None

        #sw源图宽度
        sw = img.columns()
        #sh源图高度
        sh = img.rows()
        #若目标图的宽或高都比源图大则不处理
        if (sw <= w and sh <= h):
            backImg = Image(Geometry(w, h), 'white')
            backImg.composite(img, Geometry(sw, sh, 0, 0), co.OverCompositeOp)
            backImg.profile("*", Blob())
            backImg.write(destFile)
            return "True"
        #目标的宽或高都比源图的小则进行裁剪
        elif (sw > w and sh > h):
            #源图的宽高比
            sratio = float(sw) / float(sh)
            rratio = float(w) / float(h)
            #若源图宽高比大于目标图的宽高比的话,则就高缩放,从0,0位置裁前源图宽
            #print sratio,rratio
            if (sratio > rratio):
                hscale = float(h) / float(sh)
                rw = int(sw * hscale)
                rh = int(sh * hscale)
            else:
                wscale = float(w) / float(sw)
                rw = int(sw * wscale)
                rh = int(sh * wscale)
            img.scale("%dx%d" % (rw, rh))
            img.crop(Geometry(w, h, 0, 0))
            img.profile("*", Blob())
            img.write(destFile)
            return "True"
        elif (sw > w):
            backImg = Image(Geometry(w, h), 'white')
            img.crop(Geometry(w, sh))
            backImg.composite(img, Geometry(w, h, 0, 0), co.OverCompositeOp)
            backImg.profile("*", Blob())
            backImg.write(destFile)
            return "True"
        elif (sh > h):
            backImg = Image(Geometry(w, h), 'white')
            img.crop(Geometry(sw, h))
            backImg.composite(img, Geometry(w, h, 0, 0), co.OverCompositeOp)
            backImg.profile("*", Blob())
            backImg.write(destFile)
            return "True"
        return "True"
def pgmagick_image(source, **options):
    """
    Try to open the source file using pgmagick, ignoring any errors.

    """
    # Use a StringIO wrapper because if the source is an incomplete file like
    # object, PIL may have problems with it. For example, some image types
    # require tell and seek methods that are not present on all storage
    # File objects.
    #    import ipdb; ipdb.set_trace()
    if not source:
        return
    source.open()  # If tried by a previous source_generator, will be closed
    source = StringIO(source.read())
    try:
        blob = Blob(source.read())
        image = Image(blob)
    except Exception:
        logger.exception("unable to read image to create thumbnail")
        return

    if not image.isValid():
        return

    return convertGMtoPIL(image)
Example #10
0
 def test_scale_jpeg(self):
     img = api.Image((400, 400), 'blue')
     img.write(self.tmp_filename_jpg)
     img2 = Image(Blob(open(self.tmp_filename_jpg).read()),
                  Geometry(200, 200))
     img2.scale('200x200')
     img2.write(self.tmp_filename_jpg)
Example #11
0
    def get_image(self):
        # Open the image
        try:
            img_file = urlopen(self.path)
            img_data = img_file.read()
            bytes_read = len(img_data)
        except HTTPError as e:
            raise ImageRetrievalError(self.path, "Error code: %s" % e.code)
        except URLError as e:
            raise ImageRetrievalError(self.path, e.reason)

        blob = Blob(img_data)
        image = Image(blob)
        # Check if the whole image should be used and cropped if necessary.
        src_width = image.size().width()
        src_height = image.size().height()
        if self.width != src_width or self.height != src_height:
            box = Geometry(self.width, self.height, self.x_min_src,
                           self.y_min_src)
            image.crop(box)

        # Estimates the size in Bytes of this image part by scaling the number
        # of Bytes read with the ratio between the needed part of the image and
        # its actual size.
        self.estimated_size = bytes_read * abs(
            float(self.width * self.height) / float(src_width * src_height))
        return image
Example #12
0
 def test_fromblob(self):
     with open('../example/X.jpg', 'rb') as f:
         data = f.read()
         b = Blob(data)
         img = Image(b)
         img.write('X2.jpg')
         self.assertEqual(type(img), Image)
Example #13
0
    def read(self, extension=None, quality=None):
        if quality is None: quality = self.context.request.quality

        #returns image buffer in byte format.
        img_buffer = Blob()

        ext = extension or self.extension
        try:
            self.image.magick(FORMATS[ext])
        except KeyError:
            self.image.magick(FORMATS['.jpg'])

        self.image.quality(quality)

        #available_filters = ['BesselFilter', 'BlackmanFilter', 'BoxFilter', 'CatromFilter',
        #'CubicFilter', 'GaussianFilter', 'HammingFilter', 'HanningFilter',
        #'HermiteFilter', 'LanczosFilter', 'MitchellFilter',
        #'PointFilter', 'QuadraticFilter', 'SincFilter', 'TriangleFilter']

        f = FilterTypes.CatromFilter

        self.image.filterType(f)

        self.image.write(img_buffer)

        results = img_buffer.data

        return results
Example #14
0
    def get_image(self):
        # Open the image
        try:
            r = requests.get(self.path,
                             allow_redirects=True,
                             verify=verify_ssl)
            if not r:
                raise ValueError("Could not get " + self.path)
            if r.status_code != 200:
                raise ValueError("Unexpected status code ({}) for {}".format(
                    r.status_code, self.path))
            img_data = r.content
            bytes_read = len(img_data)
        except requests.exceptions.RequestException as e:
            raise ImageRetrievalError(self.path, str(e))

        blob = Blob(img_data)
        image = Image(blob)
        # Check if the whole image should be used and cropped if necessary.
        src_width = image.size().width()
        src_height = image.size().height()
        if self.width != src_width or self.height != src_height:
            box = Geometry(self.width, self.height, self.x_min_src,
                           self.y_min_src)
            image.crop(box)

        # Estimates the size in Bytes of this image part by scaling the number
        # of Bytes read with the ratio between the needed part of the image and
        # its actual size.
        self.estimated_size = bytes_read * abs(
            float(self.width * self.height) / float(src_width * src_height))
        return image
Example #15
0
 def _get_raw_data(self, image, format_, quality, image_info=None, progressive=False):
     image.magick(format_.encode('utf8'))
     image.quality(quality)
     if format_ == 'JPEG' and progressive:
         image.interlaceType(InterlaceType.LineInterlace)
     blob = Blob()
     image.write(blob)
     return get_blob_data(blob)
Example #16
0
    def resize5(srcFile="", destFile="", w=200, h=200):
        imgs = ImageList()
        outImgs = ImageList()
        imgs.readImages(srcFile)
        gifFrameLen = len(imgs)
        #取得gif的第0帧
        img = imgs.__getitem__(0)
        #sw源图宽度
        sw = img.columns()
        sh = img.rows()
        #要缩略的宽度
        rw = w
        #要缩略的高度
        rh = h

        #源图的宽高比
        sratio = float(sw) / float(sh)
        #目标图的宽高比
        rratio = float(rw) / float(rh)

        if (sw > w):
            imgs.scaleImages("%dx" % w)
        #
        #??长大高小的图片处理问题:1600x94 转换为160x298按照宽度等比缩放
        #??长大高小的图片处理问题:1600x94 转换为522x294
        #若源图的宽高比大于目标图的宽高比时,则按照高进行缩放后再裁剪宽度
        else:
            if (sratio > rratio):
                hscale = float(rh) / float(sh)
                w = int(sw * hscale)
                h = int(sh * hscale)
                #print (sw,sh,w,h,rw,rh,hscale)
                #就高缩放
                imgs.scaleImages("%dx" % (w))

            #若源图的宽高比小于目标图的宽高比时,则按照宽进行缩放后再裁剪高度
            else:
                wscale = float(rw) / float(sw)

                w = int(sw * wscale)
                h = int(sh * wscale)
                #print (sw,sh,w,h,rw,rh,wscale)
                #就宽缩放
                imgs.scaleImages("%dx%d" % (w, h))
                #缩放完后遍历裁剪
            for i in range(gifFrameLen):
                tmpImg = imgs.__getitem__(i)
                tmpImg.crop(Geometry(rw, rh, 0, 0))
                tmpImg.profile("*", Blob())
                outImgs.append(tmpImg)
                #(102, 900, 160, 1411, 160, 298)
                #print( sw,sh,w,h,rw,rh)

        if (len(outImgs) > 0):
            outImgs.writeImages(destFile)
        else:
            imgs.writeImages(destFile)
        return "True"
Example #17
0
def deferred_pgmagick():
    im = PGImage(imagename)

    im.filterType(FilterTypes.CatromFilter)
    im.zoom(Geometry(1024, 768))

    im.quality(85)
    im.magick('jpeg')
    im.write(Blob())
Example #18
0
    def resize5(srcFile="", destFile="", w=200, h=200):

        #CONVERT_RESIZE_CROP = "%s -resize %d" + "x" + " -crop %d" + "x" + "%d" + "+0+0 +repage %s"
        img = Image(srcFile)
        sw = img.columns()
        sh = img.rows()

        #源图宽高比
        sratio = float(sw) / float(sh)
        #目标图宽高比
        tratio = float(w) / float(h)

        #若源图的宽高比大于目标图的宽高比,则
        if (sratio == tratio and (w == sw) and (h == sh)):
            imb.profile("*", Blob())
            img.write(destFile)
            return "True"
        elif (sratio > tratio):
            hscale = float(w) / float(sw)
            tw = sw * hscale
            th = sh * hscale
            img.scale("%dx" % (tw))
            if (th > h):
                img.crop(Geometry(w, h))
            img.profile("*", Blob())
            img.write(destFile)
            return "True"
        elif (sratio < tratio):
            wscale = float(w) / float(sw)

            tw = int(sw * wscale)
            th = int(sh * wscale)
            #260 132 670 502 0.388059701493 260 194

            img.scale("%dx%d" % (tw, th))
            if (th > h):
                img.crop(Geometry(w, h))
            img.profile("*", Blob())
            img.write(destFile)
            return "True"

        return "True"
Example #19
0
def get_im(content):
    if hasattr(content, 'read'):
        content = content.read()
    if not content:
        return
    else:
        try:
            f = Blob(content)
            return Image(f)
        except:
            return
Example #20
0
    def resize0(srcFile="", destFile="", w=200):

        img = Image(srcFile)
        sw = img.columns()
        sh = img.rows()
        if (sw > w):
            tw = w
            th = sh * (float(w) / float(sw))
            img.scale("%dx%d" % (tw, th))
        img.profile("*", Blob())
        img.write(destFile)
        return "True"
Example #21
0
    def resize10(srcFile="", destFile="", w=200):
        img = Image(srcFile)
        sw = img.columns()
        sh = img.rows()
        scale = sw * sh

        if (scale > w):
            tw = int(sw * ((float(w) / float(scale))**0.5))
            th = int(w / tw)
            img.scale("%dx%d" % (tw, th))
        img.profile("*", Blob())
        img.write(destFile)
        return "True"
Example #22
0
    def resize3(srcFile="",
                destFile="",
                w=200,
                h=200,
                color="",
                crop=False,
                align="center"):

        img = Image(srcFile)
        img.scale("%dx%d>" % (w, h))
        img.profile("*", Blob())
        img.write(destFile)
        return "True"
Example #23
0
    def resize9(srcFile="",
                destFile="",
                w=200,
                h=200,
                color="",
                crop=False,
                align="center"):
        img = Image(srcFile)

        #白色背景图
        backImg = None

        #sw源图宽度
        sw = img.columns()
        #sh源图高度
        sh = img.rows()

        #目标图与源图的宽比例
        wScale = float(w) / float(sw)
        #目标图与源图的高比例
        hScale = float(h) / float(sh)

        if (w > sw or h > sh):
            if (wScale == hScale):
                tw = w
                th = h
            elif (wScale < hScale):
                th = h
                tw = sw * wScale
            else:
                tw = w
                th = sh * hScale
        elif (w < sw or h < sh):
            if (wScale == hScale):
                tw = w
                th = h
            elif (wScale < hScale):
                th = h
                tw = sw * wScale
            else:
                tw = w
                th = sh * hScale
        else:
            tw = sw
            th = sh
        img.scale("%dx%d" % (tw, th))
        backImg = Image(Geometry(w, h), 'white')
        backImg.composite(img, GravityType.CenterGravity, co.OverCompositeOp)
        backImg.profile("*", Blob())
        backImg.write(destFile)
        return "True"
Example #24
0
    def applyIcc(self):
        """ Fix icc profiles """
        try:
            self.img.profile('icm')
        except:
            if self.img.colorSpace() == ColorspaceType.CMYKColorspace:
                icc_data = Blob()
                icc_data.update(open(settings['resources_path'] + 'icc/USWebUncoated.icc', 'rb').read())
                self.img.profile('icm', icc_data)

            if self.img.type() == ImageType.GrayscaleType:
                icc_data = Blob()
                icc_data.update(open(settings['resources_path'] + 'icc/sGray.icc', 'rb').read())
                self.img.profile('icm', icc_data)

        self.img.profile('!icm,*', Blob())

        icc_data = Blob()
        icc_data.update(open(settings['resources_path'] + 'icc/sRGB_v2.1bs.icc', 'rb').read())
        self.img.profile('icm', icc_data)
Example #25
0
 def test_scale_jpeg(self):
     img = api.Image((400, 400), 'blue')
     img.write(self.tmp_filename_jpg)
     with open(self.tmp_filename_jpg, 'rb') as fp:
         b = Blob(str(fp.read()))
         img2 = Image(b, Geometry(200, 200))
         if sys.platform.lower() == 'darwin':
             # NOTE: error occur when use '200x200' param
             #       -----------------------------------------------------
             #       RuntimeError: Magick: Application transferred too few
             #       scanlines (x.jpg) reported by coders/jpeg.c:344 (JPEGErrorHandler)
             img2.scale('199x199')
         else:
             img2.scale('200x200')
         img2.write(self.tmp_filename_jpg)
Example #26
0
def convertGMtoPIL(gmimage):
    """
    Convert GraphicsMagick image to PIL

    work with grayscale and colour
    """
    img = Image(gmimage)  # make copy
    gmimage.depth(8)
    img.magick("RGB")
    w, h = img.columns(), img.rows()
    blob = Blob()
    img.write(blob)
    data = blob.data

    # convert string array to an RGB PIL image
    pilimage = PilImage.fromstring('RGB', (w, h), data)
    return pilimage
Example #27
0
    def resize1(srcFile="", destFile="", w=200, h=200):
        img = Image(srcFile)
        #sw源图宽度
        sw = img.columns()
        sh = img.rows()
        #要缩略的宽度
        rw = w
        #要缩略的高度
        rh = h

        #源图的宽高比
        sratio = float(sw) / float(sh)
        #目标图的宽高比
        rratio = float(rw) / float(rh)

        #若源图的宽高比大于目标图的宽高比时,则按照高进行缩放后再裁剪宽度
        if (sratio > rratio):
            hscale = float(rh) / float(sh)
            w = sw * hscale
            h = sh * hscale
            #print (sw,sh,w,h,rw,rh,hscale)
            #就高缩放
            img.scale("%dx%d" % (w, h))
            #计算裁剪宽的部分的横坐标,超出的宽的部分进行裁剪
            tmpRowsPos = int((sw * hscale - rw) / 2)
            img.crop(Geometry(rw, rh, tmpRowsPos, 0))
        #若源图的宽高比小于目标图的宽高比时,则按照宽进行缩放后再裁剪高度
        else:
            wscale = float(rw) / float(sw)

            w = sw * wscale
            h = sh * wscale
            #print (sw,sh,w,h,rw,rh,wscale)
            #就宽缩放
            img.scale("%dx%d" % (w, h))
            tmpColsPos = int((sh * wscale - rh) / 2)
            img.crop(Geometry(rw, rh, 0, tmpColsPos))
            #只有宽大于目标宽度的时候才进行缩略
        #elif ( sw > w ):
        #    pass
        #unicodestring.encode("utf-8")
        img.profile("*", Blob())
        img.write(destFile)
        return "True"
Example #28
0
    def get_image(self):
        # Open the image
        try:
            img_file = urllib.urlopen(self.path)
        except urllib.HTTPError as e:
            raise ImageRetrievalError(self.path, "Error code: %s" % e.code)
        except urllib.URLError as e:
            raise ImageRetrievalError(self.path, e.reason)

        blob = Blob(img_file.read())
        image = Image(blob)
        # Check if the whole image should be used and cropped if necessary.
        src_width = image.size().width()
        src_height = image.size().height()
        if self.width != src_width or self.height != src_height:
            box = Geometry(self.width, self.height, self.x_min_src,
                           self.y_min_src)
            image.crop(box)
        return image
Example #29
0
def gera_xyz(imagem):
    '''
    * reduz a imagem a 25% da dimensão em pixels e converte para GIF 64 cores;
    * gera um arquivo .txt com os dados pixel a pixel, quanto às cores em RGB
      e xyz
    '''

    print messages.strings['welcome']
    print messages.strings['crexyz']

    img_base = Blob(open(imagem).read())
    img_alvo = Image(img_base)
    img_alvo.magick('GIF')
    img_alvo.colorSpace = 'XYZ'
    img_alvo.scale('25%')
    img_alvo.quantizeColors(64)
    img_alvo.quantizeDither(img_alvo.quantize(64))
    img_alvo.write('./tmp.txt')

    with open('./tmp.txt', 'r') as tt:
        return tt.readlines()
    def read(self, extension=None, quality=None):
        if quality is None:
            quality = self.context.config.QUALITY

        #returns image buffer in byte format.
        img_buffer = Blob()

        ext = extension or self.extension
        try:
            self.image.magick(FORMATS[ext])
        except KeyError:
            self.image.magick(FORMATS['.jpg'])

        if ext == '.jpg':
            self.image.interlaceType(InterlaceType.LineInterlace)
            self.image.quality(quality)
            f = FilterTypes.CatromFilter
            self.image.filterType(f)

        self.image.write(img_buffer)

        return img_buffer.data
Example #31
0
    def read(self, extension=None, quality=options.QUALITY):
        #returns image buffer in byte format.
        img_buffer = Blob()

        ext = extension or self.extension
        self.image.magick(FORMATS[ext])

        self.image.quality(quality)

        #available_filters = ['BesselFilter', 'BlackmanFilter', 'BoxFilter', 'CatromFilter', 
                             #'CubicFilter', 'GaussianFilter', 'HammingFilter', 'HanningFilter',
                             #'HermiteFilter', 'LanczosFilter', 'MitchellFilter',
                             #'PointFilter', 'QuadraticFilter', 'SincFilter', 'TriangleFilter']

        f = FilterTypes.CatromFilter

        self.image.filterType(f)

        self.image.write(img_buffer)

        results = img_buffer.data

        return results
Example #32
0
    def __init__(self, image_data: bytes):
#         try:
        blob = Blob()
        blob.update(image_data)
        self.img = pgImage()
        self.img.read(blob)
Example #33
0
 def is_valid_image(self, raw_data):
     blob = Blob()
     blob.update(raw_data)
     im = Image(blob)
     return im.isValid()
 def is_valid_image(self, raw_data):
     blob = Blob()
     blob.update(raw_data)
     im = Image(blob)
     return im.isValid()
Example #35
0
 def get_image(self, source):
     blob = Blob()
     blob.update(source.read())
     return Image(blob)
 def get_image(self, source):
     blob = Blob()
     blob.update(source.read())
     return Image(blob)