几天前在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
执行结果
相关推荐
《25行Java代码将普通图片转换为字符画图片和文本》