1. 程式人生 > >圖片轉字符圖片(二)

圖片轉字符圖片(二)

ans lac todo ref ger public des error red

序言

這個是從抖音上學來的,一開始刷抖音,遇到不少字符串跳舞的視頻,因此來實踐一下

主要分為三個部分

  1. 靜態圖片轉靜態圖片
  2. gif 轉 gif
  3. 視頻轉視頻

gif 轉 gif

原理和靜態圖片的轉換類似,這個需要每一幀的去轉換。一開始的思路是把gif的每一幀轉為圖片,然後對圖片進行轉換,最後合成 gif 。
研究了 im4java,參考: https://blog.csdn.net/DamonRush/article/details/51746995、
https://blog.csdn.net/weiwangchao_/article/details/46520571,
還有一些其他的工具(用了私有api,不推薦)
http://zhaorui1125.iteye.com/blog/2116816,
最後發現他們截出來的每一張圖要麽發紅,要麽模糊,只好放棄了。最後發現不需要把每一幀都保存下來,臨時存一下就好,具體代碼如下:

環境:
JDK 1.8

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dawn.img2text.external.AnimatedGifEncoder;
import com.dawn.img2text.external.GifDecoder;

/**
 * @ClassName: GifUtil
 * @Description: TODO
 * @author jiang
 * @date 2018年8月14日 下午9:47:29
 * 
 */
public class GifUtil {

    static Logger logger = LoggerFactory.getLogger(GifUtil.class);

    public static boolean toTextGif(final String srcFile, final String targetFile, final String base, int threshold) {

        long startTime = System.currentTimeMillis();
        try {
            GifDecoder gd = new GifDecoder();
            // 要處理的圖片
            int status = gd.read(new FileInputStream(new File(srcFile)));
            if (status != GifDecoder.STATUS_OK) {
                return false;
            }
            //
            AnimatedGifEncoder ge = new AnimatedGifEncoder();
            // 這裏是關鍵,設置要替換成透明的顏色
            ge.setTransparent(Color.WHITE);
            //
            ge.start(new FileOutputStream(new File(targetFile)));
            ge.setRepeat(0);
            for (int i = 0; i < gd.getFrameCount(); i++) {
                // 取得gif的每一幀
                BufferedImage frame = gd.getFrame(i);
                // 你可以對每一幀做點什麽,比如縮放什麽的,這裏就什麽都不做了
                int[] rgb = new int[3];
                int width = frame.getWidth();
                int height = frame.getHeight();
                int minx = frame.getMinX();
                int miny = frame.getMinY();
                int delay = gd.getDelay(i);
                BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR);
                Graphics g = tag.getGraphics();
                g.setFont(new Font("微軟雅黑", Font.PLAIN, 2));// 設置字體
                g.setColor(Color.BLACK);// 設置顏色
                for (int x = minx; x < width; x += 1) {
                    for (int y = miny; y < height; y += 1) {
                        int pixel = frame.getRGB(x, y); // 下面三行代碼將一個數字轉換為RGB數字
                        rgb[0] = (pixel & 0xff0000) >> 16;// red
                        rgb[1] = (pixel & 0xff00) >> 8;// green
                        rgb[2] = (pixel & 0xff);// blue

                        final float gray = 0.299F * rgb[0] + 0.578F * rgb[1] + 0.114F * rgb[2];
                        // index [0,base.length()),index越小顏色越深
                        final int index = Math.round(gray * (base.length() + 1) / 255);
                        if (index <= base.length() % threshold) {
                            g.drawString(String.valueOf(base.charAt(index % base.length())), x, y);// 文字的編寫及位置
                        }
                        /*-
                        if (rgb[0] + rgb[1] + rgb[2] <= 300) {
                            g.drawString(String.valueOf(base.charAt(index % base.length())), x, y);// 文字的編寫及位置
                        }*/
                    }
                }
                ge.setDelay(delay);
                ge.addFrame(tag);
            }
            // 輸出圖片
            ge.finish();
            logger.debug("{} toTextGif cost time: {}s", srcFile, System.currentTimeMillis() - startTime);
        } catch (Exception e) {
            logger.error("err", e);
            return false;
        }
        return true;
    }
}

原理和靜態圖轉字符圖片是一致,不再累述。

源碼地址:
https://github.com/Ruffianjiang/java4fun/tree/master/img2text

圖片轉字符圖片(二)