閒言少許,我先上效果圖。
左邊是原圖片,右邊是文字替換的圖片,是不是看出什麼效果?我來放大一下!
這下能看到了吧,我對你的愛,在每一個字裏行間哦~。有關程序員的強勢浪漫。實現這個效果,代碼非常簡單,真實代碼大約30行左右。完整代碼在文章最後!依舊是,程序雖然很少,但是並不簡單下面是用到的 api
java api學習手冊:https://www.matools.com/api/java8
我們在代碼中用到的類和方法。大家可以去上面鏈接學習一下哦
BufferedImage
- 構造方法
- getGraphics()
- getWidth()
- getHeight()
- getType()
- getRGB()
ImageIO:
- read()
- write()
Graphics2D
- setColor
- drawString
我來依次講解一下每行代碼的作用。
首先先定義一個我們想要在圖片中展示的內容
String base = "我愛你";
我們再讀取我們想要轉換的圖片,這裏呢,我們使用 ImageIO
中提供的靜態方法 read()
,傳入一個文件,read()
方法回返回一個 BufferedImage
類型的圖片緩存流。我們通過new File(path)
,來創建一個文件流。
BufferedImage image = ImageIO.read(new File(path));
我們再創建一個 BufferedImage
用於放置我們輸出文字的圖片。參數呢就是圖片的寬度,圖片的高度,和圖片的類型。
BufferedImage newImage = new BufferedImage(image.getWidth(),image.getHeight(), image.getType());
創建一個2D座標轉換及繪圖相關的類 Graphics2D
,用來設置每個像素點的顏色、字體大小和字體樣式。
Graphics2D graphics2d = (Graphics2D) newImage.getGraphics();
設置字體風格、樣式和大小
graphics2d.setFont(new Font("宋體", Font.BOLD, 12));
下面就是寫一個for循環,循環遍歷每一個像素點,將每隔12個像素點就替換爲文字。
index
for (int y = 0; y < image.getHeight(); y += 12) {
for (int x = 0; x < image.getWidth(); x += 12) {
//循環每一個像素點
}
}
for 循環中的的內容:獲取圖片當前位置像素的顏色
int pixel = image.getRGB(x, y);
for 循環中的的內容:分離出rgb三種顏色,分別進行灰度和二值化處理,想具體研究可以去找資料學習
int r = (pixel & 0xff0000) >> 16,
g = (pixel & 0xff00) >> 8,
b = pixel & 0xff;
for 循環中的的內容:通過graphics2d設置字體顏色
graphics2d.setColor(new Color(r, g, b));
for 循環中的的內容:在當前位置上繪上一個文字
graphics2d.drawString(String.valueOf(base.charAt(index % base.length)), x, y);
for 循環中的的內容:當前文字被繪上以後繪製下一個文字
index++;
最後,我們通過 ImageIO
方法,把圖片重新繪製,並輸出。
ImageIO.write(newImage, "JPG", new FileOutputStream("F:\\temp.jpg"));
在主方法中調用剛剛寫的方法。
public static void main(final String[] args) {
FontImage.createAsciiPic("F:\\girl.jpg");
System.out.println("OK");
}
完整代碼:
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
public class MyFontImage {
public static void createFongImg(String path){
String base = "我愛你";
try{
BufferedImage image = ImageIO.read(new File(path));
BufferedImage newImage = new BufferedImage(image.getWidth(),image.getHeight(),image.getType());
Graphics2D graphics2D = (Graphics2D) newImage.getGraphics();
graphics2D.setFont(new Font("宋體",Font.BOLD,12));
int index = 0;
for(int y = 0; y < image.getHeight(); y += 12){
for (int x = 0; x < image.getWidth(); x += 12){
int pxcolor = image.getRGB(x,y);
int r = (pxcolor & 0xff0000) >> 16,
g = (pxcolor & 0xff00) >> 8,
b = pxcolor & 0xff;
graphics2D.setColor(new Color(r, g, b));
graphics2D.drawString(String.valueOf(base.charAt(index % base.length())), x, y);
index++;
}
}
ImageIO.write(newImage, "JPG", new FileOutputStream("F:\\temp.jpg"));
}catch (Exception e){
e.printStackTrace();
}
};
public static void main(String args[]){
MyFontImage.createFongImg("F:\\girl.jpg");
System.out.println("OK");
}
}
喜歡的記得 點贊、關注 哦,不定期分享程序員的騷操作和強勢浪漫!
附之前作品精選: