示例#1
0
文件: files.py 项目: timrc/schproj
def crop(request, block):
   id = int(request.GET.get('id', -1))
   data = json.loads(request.GET.get('data', []))

   from core.models import File

   file = File.objects.get(id=id)
   file_crop_data = file.data.get('scale', {})

   from pgmagick import Image, Geometry

   file_path = '%s/%s' % (MEDIA_ROOT, file.path)
   full_file_path = '%s/%s' % (file_path, file.file_name)

   for crop_data in data:
      #
      #  do not crop same image twice
      #
      if crop_data['name'] in file_crop_data:
         local_crop_data = file_crop_data[crop_data['name']]
         if 'scaled_width' in local_crop_data and 'scaled_height' in local_crop_data and 'crop_x' in local_crop_data and 'crop_y' in local_crop_data:
            if local_crop_data['scaled_width'] == int(crop_data['scaled_width']) and local_crop_data['scaled_height'] == int(crop_data['scaled_height']) and local_crop_data['crop_x'] == int(crop_data['crop_x']) and local_crop_data['crop_y'] == int(
               crop_data['crop_y']):
               continue

      image = Image(str(full_file_path))

      g = Geometry(int(crop_data['scaled_width']), int(crop_data['scaled_height']), 0, 0)
      image.scale(g)

      gc = Geometry(int(crop_data['width']), int(crop_data['height']), int(crop_data['crop_x']), int(crop_data['crop_y']))
      image.crop(gc)

      image.quality(100)
      image.sharpen(1.0)

      full_scaled_image_path = '%s/%s_%s' % (file_path, crop_data['prefix'], file.file_name)
      image.write(str(full_scaled_image_path))

      scale_data = dict(
         width=int(crop_data['width']),
         height=int(crop_data['height']),
         scaled_width=int(crop_data['scaled_width']),
         scaled_height=int(crop_data['scaled_height']),
         crop_x=int(crop_data['crop_x']),
         crop_y=int(crop_data['crop_y']),
         center_x=crop_data['center_x'],
         center_y=crop_data['center_y'],
         quality=100,
         sharpen=1.0,
         prefix=crop_data['prefix'],
         name=crop_data['name'],
         cropped=True
      )

      file.data['scale'][crop_data['name']] = scale_data

   file.save()

   return dict(status='success', message='Image %s was successfully cropped.' % file.title, id=id)
示例#2
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
示例#3
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
示例#4
0
    def get_image( self ):
        # Open the image
        try:
            img_file = urllib.urlopen( self.path )
            img_data = img_file.read()
            bytes_read = len(img_data)
        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_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
示例#5
0
 def get_image( self ):
     # Open the image
     img_file = urllib.urlopen( self.path )
     blob = Blob( img_file.read() )
     image = Image( blob )
     # Check if the whole image should be used and croped
     # 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
示例#6
0
    def convert_split(srcfile='', dstpath='', truefile='', split='3x3', w=100, h=100):
        """
        目前仅用作封面频道
        """
        srcfile = srcfile.encode("utf-8")
        dstpath = dstpath.encode("utf-8")
        truefile = truefile.encode("utf-8")
        (sp_x, sp_y) = split.split('x')
        (file_name, image_ext) = os.path.splitext(os.path.basename(srcfile))

        cw = int(sp_x) * int(w)
        ch = int(sp_y) * int(h)
        t1 = time.time()
        #生成封面列表图
        re = myGraphicsMagick.convert_gif_thumbnail_frame0_g(srcfile=srcfile, dstfile=truefile, w=cw, h=ch,
            need_return=False)


        if re == True:
            #切割方式为从图片的左上开始逐行切割
            #目标图片文件名为:50d8059b1a822.11.jpg
            blobData = Blob(open(srcfile).read())

            try:
                num = 0#图片输出的编号
                for j in range(int(sp_y)):

                    if ( num >= ( int( sp_x )*int( sp_y ) - 1 ) ):
                        break
                    for i in range(int(sp_x)):
                        img = Image( blobData, Geometry(cw,ch) )
                        linePos = i * int(w)
                        colsPos = j * int(h)
                        #从指定的像素点进行裁剪
                        img.crop( Geometry(w,h,linePos, colsPos) )
                        destFilename = dstpath+'/%s.%d.%s' %( file_name,num,image_ext )
                        img.profile("*",Blob())
                        img.write( destFilename )
                        num = num + 1
                t2 = time.time()
                sys.stdout.writelines(datetime.now().strftime('%Y-%m-%d %H:%M:%S  ')+"libconvert appName:%s ver:%s cmdSN:%s type:%s cmdData:%s command : convert_split srcfile:%s dstfile:%s runTime:%s\n" % ( proto.protocal['appName'],proto.protocal['ver'],proto.protocal['cmdSN'],proto.protocal['type'],proto.protocal['cmdData'], srcfile,dstfile,(t2-t1)) )
                sys.stdout.flush()
                return ret
            except Exception as e:
                sys.stderr.writelines(datetime.now().strftime('%Y-%m-%d %H:%M:%S  ')+"libconvert_split %s %s srcfile:%s destFilename:%s\n" % (e.args, e.message, srcfile,destFilename))
                sys.stderr.flush()
                return 'False'
        else:
            return "False"
            pass
        return 'True'
示例#7
0
 def execute(self, context):
     downloaded_thumbnail = context["task_instance"].xcom_pull(
         self.get_inputs_from)
     if downloaded_thumbnail is None:
         log.info("Nothing to process.")
         return
     log.info("downloaded_thumbnail: {}".format(downloaded_thumbnail))
     img = Image(downloaded_thumbnail)
     least_dim = min(int(img.columns()), int(img.rows()))
     img.crop("{dim}x{dim}".format(dim=least_dim))
     img.scale(self.thumb_size_x+'x'+self.thumb_size_y)
     img.scale("{}x{}".format(self.thumb_size_x, self.thumb_size_y))
     output_path = os.path.join(
         os.path.dirname(downloaded_thumbnail), "thumbnail.jpeg")
     img.write(output_path)
     return output_path
示例#8
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
示例#9
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"
示例#10
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"
示例#11
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
示例#12
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 )):
            img.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"
示例#13
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"
示例#14
0
def enhanceImage(localpath):
    """Crop to 50%, and resize to original size
        sharpen, save out to same image name
        Returns True if image processing succeeds"""
    try:
        img = Image(localpath)

        size = img.size()
        geo = Geometry(round(size.width() * 0.5), round(size.height() * 0.5),
                       round(size.width() * 0.25), round(size.height() * 0.25))
        img.crop(geo)
        img.scale(size)
        img.quality(80)
        img.sharpen(1)
        img.write(localpath)
        print("Image written to %s" % localpath)
    except:
        return False

    return True
示例#15
0
    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"
示例#16
0
    def generate(self, source_path, small_thumb_path, large_thumb_path):
        img = Image(source_path)

        width = img.size().width()
        height = img.size().height()

        # Detect if we need to rotate the image by reading EXIF data
        orientation = 0
        if img.attribute("EXIF:Orientation") != "unknown":
            try:
                orientation = int(img.attribute("EXIF:Orientation"))
            except ValueError:
                print ("Invalid EXIF orientation, using default")

        # Detect if we need to resize the large thumbnail
        if width > LARGE_MAX_WIDTH:
            height = int((float(height) / width) * LARGE_MAX_WIDTH)
            width = LARGE_MAX_WIDTH
        elif height > LARGE_MAX_HEIGHT:
            width = int((float(width) / height) * LARGE_MAX_HEIGHT)
            height = LARGE_MAX_HEIGHT

        # Rescale the large thumbnail if dimensions doesn't match
        if width != img.size().width() or height != img.size().height():
            img.sample("!%sx%s" % (width, height))

        # Rotate the image if needed
        if orientation == 6:
            img.rotate(90)
        elif orientation == 8:
            img.rotate(-90)

        self.write_image(img, large_thumb_path)

        # Crop the small thumbnail and then resize it to the correct size
        img.crop("%sx%s" % (min(width, height), min(width, height)))
        img.sample("%sx%s" % (SMALL_WIDTH_AND_HEIGHT, SMALL_WIDTH_AND_HEIGHT))

        self.write_image(img, small_thumb_path)
示例#17
0
    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"
示例#18
0
    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"
示例#19
0
    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"
示例#20
0
parser.add_argument('infiles', nargs='*', type=argparse.FileType('r'), default=sys.stdin)
parser.add_argument('-o', default="split%d.pnm")
args = parser.parse_args()

number = 0
outpattern = args.o

for file in args.infiles:
  blob = Blob(file.read())
  file.close()

  # upper half
  im = Image(blob)
  width = im.columns()
  height = im.rows() // 2
  geo = Geometry( '%dx%d' % (width,height) )
  im.crop(geo)
  im.write(outpattern % number)

  # lower half
  im = Image(blob)
  width = im.columns()
  height = im.rows() // 2
  geo = Geometry( '%dx%d+0+%d' % (width,height,height) )
  im.crop(geo)
  im.rotate(180)
  im.write(outpattern % (number + 1))

  number += 2

示例#21
0
def export_area(x1, y1, z1, x2, y2, z2, chunks, assets, data):

    if x1 > x2:
        x1, x2 = x2, x1
    if y1 > y2:
        y1, y2 = y2, y1
    if x1 > x2:
        z1, z2 = z2, z1

    cache = {}

    unknow = Image(Geometry(16, 16), "fuchsia")
    hardcoded = {
        'minecraft:air': Color('white'),
        'minecraft:cave_air': Color('black'),
        'minecraft:water':
        Color('blue'),  # TODO use 'block/water_still' with #0080ff tint
        'minecraft:lava': 'block/lava_still',
    }
    for x in hardcoded:
        if isinstance(hardcoded[x], Color):
            hardcoded[x] = Image(Geometry(16, 16), hardcoded[x])
        else:
            hardcoded[x] = Image("%s/textures/%s.png" %
                                 (assets.directory, hardcoded[x]))
            hardcoded[x].crop(Geometry(16, 16))

    for y in range(y2 - y1):
        img = Image(Geometry(16 * (x2 - x1), 16 * (z2 - z1)), 'transparent')
        for z in range(z2 - z1):
            for x in range(x2 - x1):
                try:
                    i = None
                    sid = chunks.get_block_at(x + x1, y + y1, z + z1)
                    if sid in cache:
                        i = cache[sid]
                    else:
                        bloc = data.blocks_states[sid]
                        if bloc in hardcoded:
                            i = hardcoded[bloc]
                        else:
                            prop = data.blocks_properties[sid]
                            variant = assets.get_block_variant(bloc, prop)

                            if 'model' in variant:
                                faces = assets.get_faces_textures(
                                    assets.get_model(variant['model']))
                                if 'up' in faces:
                                    up = faces['up']
                                    i = Image(
                                        "%s/textures/%s.png" %
                                        (assets.directory, up['texture']))
                                    if "uv" in up:
                                        pass  # TODO
                                    i.crop(Geometry(16, 16))
                                    if "tintindex" in up:
                                        tint = '#80ff00'
                                        ti = Image(Geometry(16, 16), tint)
                                        i.composite(
                                            ti, 0, 0, CompositeOperator.
                                            MultiplyCompositeOp)
                        if not i:
                            i = unknow
                        cache[sid] = i

                    img.composite(i, x * 16, z * 16,
                                  CompositeOperator.OverCompositeOp)
                except Exception:
                    continue

        img.write("/tmp/slice_%d.png" % (y))
示例#22
0
    def convert_split(srcfile='',
                      dstpath='',
                      truefile='',
                      split='3x3',
                      w=100,
                      h=100):
        """
        目前仅用作封面频道
        """
        srcfile = srcfile.encode("utf-8")
        dstpath = dstpath.encode("utf-8")
        truefile = truefile.encode("utf-8")
        (sp_x, sp_y) = split.split('x')
        (file_name, image_ext) = os.path.splitext(os.path.basename(srcfile))

        cw = int(sp_x) * int(w)
        ch = int(sp_y) * int(h)
        t1 = time.time()
        #生成封面列表图
        re = myGraphicsMagick10.convert_gif_thumbnail_frame0_g(
            srcfile=srcfile, dstfile=truefile, w=cw, h=ch, need_return=False)

        if re == True:
            #切割方式为从图片的左上开始逐行切割
            #目标图片文件名为:50d8059b1a822.11.jpg
            blobData = Blob(open(srcfile).read())

            try:
                num = 0  #图片输出的编号
                for j in range(int(sp_y)):

                    if (num >= (int(sp_x) * int(sp_y) - 1)):
                        break
                    for i in range(int(sp_x)):
                        img = Image(blobData, Geometry(cw, ch))
                        linePos = i * int(w)
                        colsPos = j * int(h)
                        #从指定的像素点进行裁剪
                        img.crop(Geometry(w, h, linePos, colsPos))
                        destFilename = dstpath + '/%s.%d.%s' % (file_name, num,
                                                                image_ext)
                        img.profile("*", Blob())
                        img.write(destFilename)
                        num = num + 1
                t2 = time.time()
                sys.stdout.writelines(
                    datetime.now().strftime('%Y-%m-%d %H:%M:%S  ') +
                    "libconvert appName:%s ver:%s cmdSN:%s type:%s cmdData:%s command : convert_split srcfile:%s dstfile:%s runTime:%s\n"
                    % (proto.protocal['appName'], proto.protocal['ver'],
                       proto.protocal['cmdSN'], proto.protocal['type'],
                       proto.protocal['cmdData'], srcfile, dstfile, (t2 - t1)))
                sys.stdout.flush()
                return ret
            except Exception as e:
                sys.stderr.writelines(
                    datetime.now().strftime('%Y-%m-%d %H:%M:%S  ') +
                    "libconvert_split %s %s srcfile:%s destFilename:%s\n" %
                    (e.args, e.message, srcfile, destFilename))
                sys.stderr.flush()
                return 'False'
        else:
            return "False"
            pass
        return 'True'