幾天前在CSDN問答上看到這個問題,想聯系提問者,告訴他,我解決了,可是一直沒有聯系上, 于是決定把實作代碼以文章的形式發出來,

思路:
將原圖,豎向劃分為10個等份,前兩個等份作為1個參考圖,后8份作為1張樣本圖,所以總共需要分割9張圖出來(第一張占兩份),然后將第一張參考圖和后面8張樣本圖合并成8個樣本結果即可,
實作
新建普通java 專案,Java單類實作代碼,復制到java專案中,用idea編輯器 主方法運行,(引入的Class 都是JDK中自有的)
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class ImageUtil {
public static BufferedImage cutIO(int x, int y, int width, int height, BufferedImage img) {
int[] imgRgb = new int[width * height];
System.out.println(x+" "+y+" "+width+" "+height);
img.getRGB(x, y, width, height, imgRgb, 0, width);
BufferedImage newImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
newImage.setRGB(0, 0, width, height, imgRgb, 0, width);
return newImage;
}
public static void cut(int x, int y, int width, int height, BufferedImage img, Integer num) {
BufferedImage newImage = cutIO(x,y,width,height,img);
newImage.setRGB(0, 0, width, height, new int[width * height], 0, width);
try {
ImageIO.write(newImage, "PNG", new File("C:\\Users\\tarzan\\Desktop\\image\\"+num+".png"));
} catch (IOException e) {
e.printStackTrace();
}
}
public static void exec(String IMG) throws IOException {
BufferedImage image = ImageIO.read(new File(IMG));
int w=image.getWidth();
int d=w/10;
int h=image.getHeight();
BufferedImage first = cutIO(0,0,d*2,h,image);;
for (int i = 1; i < 9; i++) {
BufferedImage img= cutIO(d*(i+1),0,d,h,image);
mergeImage(first,img,"C:\\Users\\tarzan\\Desktop\\image\\0_"+(i)+".png");
}
}
public static void mergeImage(String imgPath1,String imgPath2,String margeImgPath){
try {
BufferedImage bi_1 = ImageIO.read(new File(imgPath1));
BufferedImage bi_2 = ImageIO.read(new File(imgPath2));
mergeImage(bi_1,bi_2,margeImgPath);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void mergeImage(BufferedImage bi_1,BufferedImage bi_2,String margeImgPath){
try{
//假設圖片1 和圖片2 高度相同,左右合成
//new 一個新的影像
int w_1 = bi_1.getWidth();
int w_2 = bi_2.getWidth();
int h= bi_1.getHeight();
int w= w_1 + w_2;
BufferedImage bi=new BufferedImage(w,h,BufferedImage.TYPE_4BYTE_ABGR);
//像素一個一個復制過來
for(int y=0; y<h; y++){
for(int x=0;x<w_1;x++){
bi.setRGB(x,y,bi_1.getRGB(x,y));
}
}
for(int y=0;y<h;y++){
for(int x=0;x<w_2;x++){
bi.setRGB(w_1+x,y,bi_2.getRGB(x,y));
}
}
//輸出檔案
ImageIO.write(bi,"png",new File(margeImgPath));
}catch(IOException ex){
ex.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
exec("C:\\Users\\tarzan\\Desktop\\image\\test.png");
// mergeImage("C:\\Users\\tarzan\\Desktop\\image\\1.png","C:\\Users\\tarzan\\Desktop\\image\\2.png","C:\\Users\\tarzan\\Desktop\\image\\1_2.png");
}
}
執行結果

相關推薦
《25行Java代碼將普通圖片轉換為字符畫圖片和文本》
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/281243.html
標籤:java
下一篇:資料結構:哈希表
