先看一下效果图吧:
[img]http://dl2.iteye.com/upload/attachment/0090/4345/53747855-5942-3d23-b8c7-ef76d810e14d.jpg[/img]
主要的代码如下:
[img]http://dl2.iteye.com/upload/attachment/0090/4345/53747855-5942-3d23-b8c7-ef76d810e14d.jpg[/img]
主要的代码如下:
package sea;
import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Positions;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* User: Greta.Wang
* Date: 12-11-3
* Read nine pictures from file system, and compose them to one, in the process, each picture will be added a watermark.
*/
public class ComposePicture {
public static void main(String args[])
throws IOException {
//从工程中去读九张图片,并对图片做进一步的处理(缩小比例,旋转30度,加水印),并把图片保存在内存中做进一步的处理
List<BufferedImage> bufferedImageList = readPicturesToMemory();
//在内存中,合并九张图片成一张图片
BufferedImage bufferedImageNineByNine = composeNinePicturesToOne(bufferedImageList);
//把内存中的图片写入到指定的文件中
File fileOutPut = new File(System.getProperty("user.dir") + "/handledpictures/compose.jpg");
ImageIO.write(bufferedImageNineByNine, "jpg", fileOutPut);
}
public static List<BufferedImage> readPicturesToMemory()
throws IOException {
String[] pathArray = new String[9];
List<BufferedImage> bufferedImageList = new ArrayList<BufferedImage>();
//Thumbnail读取水印文件到内存中
BufferedImage waterMarkBufferedImage = Thumbnails.of(ComposePicture.class.getClassLoader().getResource("5.png").getFile())
//Thumbnail的方法,根据比例缩小,0.4f意思是缩小到原图的40%
.scale(0.4f)
//读取成BufferedImage对象
.asBufferedImage();
//读取9张待处理的图片到内存中
for (int i = 0; i < 9; i++) {
//取得图片的路径
pathArray[i] = ComposePicture.class.getClassLoader().getResource("IMG_000" + i + ".JPG").getFile();
BufferedImage image = Thumbnails.of(pathArray[i])
//按比例缩小
.scale(0.05f)
//加水印,0.5f表示的是透明度
.watermark(Positions.CENTER, waterMarkBufferedImage, 0.5f)
//旋转30度
.rotate(30)
//读取成BufferedImage对象
.asBufferedImage();
bufferedImageList.add(image);
}
return bufferedImageList;
}
public static BufferedImage composeNinePicturesToOne(List<BufferedImage> bufferedImageList) {
//取得处理后图像的宽度和高度,要处理的9张图片有相同的高度和宽度
int width = bufferedImageList.get(0).getWidth();
int height = bufferedImageList.get(0).getHeight();
List<int[]> imageArrayList = new ArrayList<int[]>();
for (BufferedImage bufferedImage : bufferedImageList) {
int[] oneImageArray = new int[width * height];
//读取图片成byte数组
oneImageArray = bufferedImage.getRGB(0, 0, width, height, oneImageArray, 0, width);
imageArrayList.add(oneImageArray);
}
//合并图片到同一个bufferedImage对象中
BufferedImage bufferedImageNineByNine = new BufferedImage(width * 3, height * 3, BufferedImage.TYPE_INT_RGB);
int x = 0;
int y = 0;
//根据x,y的坐标,先输出x轴上的三张,然后输出y轴上的图片
for (int[] buffered : imageArrayList) {
bufferedImageNineByNine.setRGB(width * y, height * x, width, height, buffered, 0, width);
y++;
if (y % 3 == 0) {
y = 0;
x++;
}
}
return bufferedImageNineByNine;
}
}