前言
由于业务需求,需要将一个打图片切成若干小图片。
图片基本是比较规则的,切成若干行和列,如一个大图片有4个国家的国旗图片,2行2列,需要切成4个同样大小的小图。
从本地文件获取图片切图
public class ImageSlicer {
public static void main(String[] args) {
try {
File input = new File("iron.png");
BufferedImage originalImg = ImageIO.read(input);
int width = originalImg.getWidth();
int height = originalImg.getHeight();
// 设定每一小图的宽高
int sliceWidth = width / 2; // 这里将图片切分为4部分,每部分的宽度为原始图片宽度的一半
int sliceHeight = height / 2; // 每部分的高度为原始图片高度的一半
BufferedImage sliceImg;
// 对原始图片进行切割
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
sliceImg = originalImg.getSubimage(i * sliceWidth, j * sliceHeight, sliceWidth, sliceHeight);
// 将切割出的图片保存为新的文件
String str = input.getName().substring(0, input.getName().indexOf("."));
ImageIO.write(sliceImg, "png", new File(str + i + "_" + j + ".png"));
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
//这段代码将 "input.jpg" 这个图片按照宽度和高度均分为四部分,并保存为四个新的文件:
// output_0_0.jpg,output_0_1.jpg,output_1_0.jpg,output_1_1.jpg。
// 你可以根据需要调整切分的大小和保存的文件名。注意,这个代码没有处理图片不能被等分的情况,
// 如果原图的大小不能被切分的大小整除,可能会丢失一部分图像数据。
2.从网络获取图片并切图
public class CutImage2Pieces {
public static void main(String[] args) throws IOException {
// Setting Chrome as an agent
System.setProperty("http.agent", "Chrome");
// reading the original image file
// File file = new File("https://www.educative.io/api/edpresso/shot/5120209133764608/image/5075298506244096/test.jpg");
// FileInputStream sourceFile = new FileInputStream(file);
// reading the file from a URL
URL url = new URL("https://www.educative.io/api/edpresso/shot/5120209133764608/image/5075298506244096/test.jpg");
InputStream is = url.openStream();
BufferedImage image = ImageIO.read(is);
// initalizing rows and columns
int rows = 4;
int columns = 4;
// initializing array to hold subimages
BufferedImage imgs[] = new BufferedImage[16];
// Equally dividing original image into subimages
int subimage_Width = image.getWidth() / columns;
int subimage_Height = image.getHeight() / rows;
int current_img = 0;
// iterating over rows and columns for each sub-image
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
// Creating sub image
imgs[current_img] = new BufferedImage(subimage_Width, subimage_Height, image.getType());
Graphics2D img_creator = imgs[current_img].createGraphics();
// coordinates of source image
int src_first_x = subimage_Width * j;
int src_first_y = subimage_Height * i;
// coordinates of sub-image
int dst_corner_x = subimage_Width * j + subimage_Width;
int dst_corner_y = subimage_Height * i + subimage_Height;
img_creator.drawImage(image, 0, 0, subimage_Width, subimage_Height, src_first_x, src_first_y, dst_corner_x, dst_corner_y, null);
current_img++;
}
}
//writing sub-images into image files
for (int i = 0; i < 16; i++) {
File outputFile = new File("img" + i + ".jpg");
ImageIO.write(imgs[i], "jpg", outputFile);
}
System.out.println("Sub-images have been created.");
}
}
总结
感谢提供此功能代码的大佬。之前搜索到的,忘记出处了。