コード例 #1
0
    def auto_crop(self, output_path):
        try:
            im = Image.open(task.utf8_to_file_charset(output_path))
            if im.mode != 'RGB':
                im = im.convert("RGB")

            cropped = autoCrop(im)
            cropped.save(task.utf8_to_file_charset(output_path),
                         'JPEG',
                         quality=100)
        except:
            self.logger_object.exception('auto crop (%s) failed',
                                         output_path.decode('utf8'))
コード例 #2
0
 def get_video_duration(self, input_filepath):
     duration = 0
     cmd = self.cmd_video_duration_fmt % addslashes(input_filepath)
     # self.logger_object.info('get duration cmd (%s)' % cmd.decode('utf8'))
     try:
         p = subprocess.Popen(task.utf8_to_file_charset(cmd),
                              shell=True,
                              stdout=subprocess.PIPE,
                              stderr=subprocess.STDOUT)
         lines = p.stdout.readlines()
         if not lines:
             return 0
         out = lines[0]
         retval = p.wait()
         if retval:
             return duration
         # 00:05:52.60
         # dlist = re.split(':|.', out)
         dlist = out.split(':')
         duration = int(dlist[0]) * 3600 + int(dlist[1]) * 60 + int(
             dlist[2].split('.')[0])
         self.logger_object.info('get duration (%d)' % duration)
     except:
         self.logger_object.exception('get duration (%s) failed',
                                      cmd.decode('utf8'))
     return duration
コード例 #3
0
    def make_image_size_thumbnail(self, input_filepath, output_filepath, size,
                                  mode):
        size_xy = size.split('x')
        if mode == 'resize':
            im = Image.open(task.utf8_to_file_charset(input_filepath))
            if im.mode != 'RGB':
                im = im.convert("RGB")

            nim = im.resize((int(size_xy[0]), int(size_xy[1])), Image.BILINEAR)
            nim.save(task.utf8_to_file_charset(output_filepath),
                     'JPEG',
                     quality=100)
        elif mode == 'ratio':
            resize_ratio_img(task.utf8_to_file_charset(input_filepath),
                             task.utf8_to_file_charset(output_filepath),
                             int(size_xy[0]), int(size_xy[1]), 75)
        elif mode == 'pad':
            im = Image.open(task.utf8_to_file_charset(input_filepath))
            if im.mode != 'RGB':
                im = im.convert("RGB")

            size = (int(size_xy[0]), int(size_xy[1]))
            im.thumbnail(
                size,
                Image.ANTIALIAS)  # generating the thumbnail from given size

            offset_x = max((size[0] - im.size[0]) / 2, 0)
            offset_y = max((size[1] - im.size[1]) / 2, 0)
            offset_tuple = (offset_x, offset_y)  # pack x and y into a tuple

            final_thumb = Image.new(
                mode='RGB', size=size,
                color=(0, 0,
                       0))  # create the image object to be the final product
            final_thumb.paste(
                im,
                offset_tuple)  # paste the thumbnail into the full sized image
            final_thumb.save(task.utf8_to_file_charset(output_filepath),
                             'JPEG',
                             quality=100)

        elif mode == 'crop':
            im = Image.open(task.utf8_to_file_charset(input_filepath))
            if im.mode != 'RGB':
                im = im.convert("RGB")

            nim = ImageOps.fit(im, (int(size_xy[0]), int(size_xy[1])),
                               Image.ANTIALIAS)
            nim.save(task.utf8_to_file_charset(output_filepath),
                     'JPEG',
                     quality=100)
        else:
            return False
        if task.check_file_exist(output_filepath):
            return True

        return False
コード例 #4
0
    def make_one_video_thumbnail(self, pos, video_path, tn_video_image_path):

        cmd = self.cmd_tn_video_fmt % (pos, addslashes(video_path),
                                       addslashes(tn_video_image_path))
        self.logger_object.info('cmd (%s)' % cmd.decode('utf8'))

        try:
            p = subprocess.Popen(task.utf8_to_file_charset(cmd),
                                 shell=True,
                                 stdout=subprocess.PIPE,
                                 stderr=subprocess.STDOUT)
            p.wait()
            if task.check_file_exist(tn_video_image_path):
                return True
            else:
                return False
        except:
            self.logger_object.exception('(%s) failed', cmd.decode('utf8'))
        return False
コード例 #5
0
    def make_image_backcolor_thumbnail(self, input_filepath, output_filepath,
                                       backcolor):
        cmd = self.cmd_tn_image_backcolor_fmt % (
            backcolor, addslashes(input_filepath), addslashes(output_filepath))

        self.logger_object.info('cmd (%s)' % cmd.decode('utf8'))

        try:
            p = subprocess.Popen(task.utf8_to_file_charset(cmd),
                                 shell=True,
                                 stdout=subprocess.PIPE,
                                 stderr=subprocess.STDOUT)
            p.wait()
            if task.check_file_exist(output_filepath):
                return True
            else:
                return False
        except:
            self.logger_object.exception('(%s) failed', cmd.decode('utf8'))
        return False
コード例 #6
0
 def get_image_color(self, input_filepath):
     """通过样本方差,检测颜色的丰富程度"""
     color_threshold = 0
     cmd = self.cmd_color_threshold_fmt % addslashes(input_filepath)
     self.logger_object.info('cmd (%s)' % cmd.decode('utf8'))
     try:
         p = subprocess.Popen(task.utf8_to_file_charset(cmd),
                              shell=True,
                              stdout=subprocess.PIPE,
                              stderr=subprocess.STDOUT)
         out = p.stdout.readlines()[0]
         # print out
         retval = p.wait()
         if retval:
             return color_threshold
         color_threshold = int(float(out))
     except:
         self.logger_object.exception('check_image_color (%s) failed',
                                      cmd.decode('utf8'))
     return color_threshold
コード例 #7
0
 def make_pdf_thumbnail(self, input_path, output_path):
     cmd = self.cmd_tn_pdf_fmt % (addslashes(output_path),
                                  addslashes(input_path))
     self.logger_object.info('cmd (%s)' % cmd.decode('utf8'))
     ret = False
     try:
         p = subprocess.Popen(task.utf8_to_file_charset(cmd),
                              shell=True,
                              stdout=subprocess.PIPE,
                              stderr=subprocess.STDOUT)
         p.wait()
         if task.check_file_exist(output_path):
             ret = True
         else:
             ret = False
     except:
         self.logger_object.exception('make pdf thumbnail (%s) failed',
                                      cmd.decode('utf8'))
     if ret:
         self.auto_crop(output_path)
     return ret
コード例 #8
0
    def make_thumbnail(self, param_dict):
        """video- thumbnail-size-color"""

        mediaformat = param_dict['mediaformat']
        # 检测图片是否存在 1 video 2 image
        # thumbnail

        # 随着裁剪会发生改变

        # 0x0表示原始图像
        # 不同尺寸的海报都基于此生成
        # 命名规则 orgfilename lb _poster|tposter time size backcoror ext

        if (mediaformat == task.URL_TYPE_VIDEO) and (
                'time' in param_dict) and (param_dict['time']
                                           not in ['0-0', '0']):
            stime, etime = param_dict['time'].split('-')
            name_lb = "_lb"
            name_time = "_" + param_dict['time']
        else:
            name_lb = ''
            name_time = ''
            stime = 0
            etime = 0

        crop_base_poster_path = "%s%s_poster%s%s" % (
            param_dict['input'], name_lb, name_time, self.poster_ext)
        # print '海报:%s' % (crop_base_poster_path)
        self.logger_object.info('海报:%s' % (crop_base_poster_path))
        if mediaformat != task.URL_TYPE_IMAGE:
            # 未裁剪的海报
            poster_path = "%s%s_tposter%s_0x0_0.png" % (param_dict['input'],
                                                        name_lb, name_time)
            if param_dict['force'] == 1 or (not os.path.exists(
                    task.utf8_to_file_charset(poster_path))):
                if mediaformat == task.URL_TYPE_DOCUMENT:
                    ext = os.path.splitext(param_dict['input'])[1][1:].lower()
                    if ext == 'pdf' and os.path.exists(
                            task.utf8_to_file_charset(param_dict['input'])):
                        pdf_file = param_dict['input']
                    elif os.path.exists(
                            task.utf8_to_file_charset(param_dict['input'] +
                                                      "_text.pdf")):
                        pdf_file = param_dict['input'] + "_text.pdf"

                    else:
                        print "format not support"
                        return False
                    if not self.make_pdf_thumbnail(pdf_file, poster_path):
                        print "make pdf thumbnail failed"
                        return False
                elif mediaformat == task.URL_TYPE_VIDEO:
                    # print 'poster_path:%s' % (poster_path)
                    self.logger_object.info('poster_path:%s' % (poster_path))
                    if not self.make_video_thumbnail(param_dict['input'],
                                                     poster_path, int(stime),
                                                     int(etime)):
                        return False
                # todo 三分频课件,从目录中找到视频文件
                elif mediaformat == task.URL_TYPE_ONLINE_COURSE:
                    return False
                else:  # unsupport format
                    return False

                shutil.copyfile(
                    task.utf8_to_file_charset(poster_path),
                    task.utf8_to_file_charset(crop_base_poster_path))
                poster_dir, file_name = os.path.split(param_dict['input'])
                remove_files(
                    task.utf8_to_file_charset(poster_dir),
                    task.utf8_to_file_charset(
                        "%s%s_tposter%s*%s" %
                        (file_name, name_lb, name_time, self.poster_ext)),
                    False, "%s%s_tposter%s_0x0_0.png" %
                    (file_name, name_lb, name_time))

        else:
            # 图像文件,未裁剪海报就是他本身
            poster_path = param_dict['input']

        if param_dict['end'] not in ['0x0', '0']:
            start = param_dict['start'].split('x')
            end = param_dict['end'].split('x')
            im = Image.open(task.utf8_to_file_charset(poster_path))
            if im.mode != 'RGB':
                im = im.convert("RGB")
            nim = im.crop(
                (int(start[0]), int(start[1]), int(end[0]), int(end[1])))
            nim.save(task.utf8_to_file_charset(crop_base_poster_path),
                     'JPEG',
                     quality=100)
            #     批量移除生成的其他缩略图
            poster_dir, file_name = os.path.split(param_dict['input'])
            remove_files(
                task.utf8_to_file_charset(poster_dir),
                task.utf8_to_file_charset(
                    "%s%s_tposter%s*%s" %
                    (file_name, name_lb, name_time, self.poster_ext)), False,
                "%s%s_tposter%s_0x0_0.png" % (file_name, name_lb, name_time))
        # 为了兼容性考虑,如果之前生成了.png格式,则还是采用png
        if not os.path.exists(
                task.utf8_to_file_charset(crop_base_poster_path)):
            if mediaformat == task.URL_TYPE_IMAGE:
                crop_base_poster_path = param_dict['input']
            else:
                crop_base_poster_path = "%s%s_poster%s.png" % (
                    param_dict['input'], name_lb, name_time)

        # size
        if param_dict['size'] in ['0x0', '0']:
            tn_size_image_path = crop_base_poster_path
        else:
            tn_size_image_path = "%s%s_tposter%s_%s_0%s" % (
                param_dict['input'], name_lb, name_time, param_dict['size'],
                self.poster_ext)
            if (param_dict['force'] == 1
                    or not task.check_file_exist(tn_size_image_path)):
                if not self.make_image_size_thumbnail(
                        crop_base_poster_path, tn_size_image_path,
                        param_dict['size'], param_dict['mode']):
                    return False

        # unsupport todo 通过pil 而不是 vignette2来生成背景色
        # if param_dict['backcolor'] != '0':
        #     if param_dict['tnfmt'] == 1:
        #         tn_backcolor_image_path = "%s%s_tposter%s_%s_%s%s" % (
        #             param_dict['input'], name_lb, name_time, param_dict['size'], param_dict['backcolor'], self.poster_ext)
        #     if (param_dict['force'] == 1 or
        #             not task.check_file_exist(tn_backcolor_image_path)):
        #         if not self.make_image_backcolor_thumbnail(tn_size_image_path, tn_backcolor_image_path, param_dict['backcolor']):
        #             return False
        return True