Ejemplo n.º 1
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
Ejemplo n.º 2
0
    def make_video_thumbnail(self,
                             video_path,
                             tn_video_image_path,
                             stime=0,
                             etime=0):
        max_color = 0
        max_color_position = 0

        # 多次尝试,有可能源文件被删除了, 优先采用原清
        fix_video_path = ''
        if task.check_file_exist(video_path + "_yq.mp4"):
            fix_video_path = video_path + "_yq.mp4"
        elif task.check_file_exist(video_path + "_cq.mp4"):
            fix_video_path = video_path + "_cq.mp4"
        elif task.check_file_exist(video_path):
            fix_video_path = video_path
        else:
            self.logger_object.info('video_path not exist (%s) ' %
                                    video_path.decode('utf8'))
            return False
        duration = self.get_video_duration(fix_video_path)
        print(fix_video_path)
        if duration == 0:
            return False
        if etime > 0:
            duration = min(etime, duration)
        for i in range(1, self.try_times):
            pos = random.randint(stime, duration)
            if self.make_one_video_thumbnail(pos, fix_video_path,
                                             tn_video_image_path):
                color = self.get_image_color(tn_video_image_path)
                if color >= self.color_threshold:
                    return True
                else:
                    if color > max_color:
                        max_color_position = pos
                        max_color = color
        # 挑一张最好的
        return self.make_one_video_thumbnail(max_color_position,
                                             fix_video_path,
                                             tn_video_image_path)
Ejemplo n.º 3
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
Ejemplo n.º 4
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
Ejemplo n.º 5
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
Ejemplo n.º 6
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