Java端小图平铺合并成一个大图的代码

平铺合并

pc版本测试成功

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/**
* 将一个小图从左到右, 从上到下 连续的合并为一个大图
* @param srcPng 需要合成的小图片路径及名称
* @param outPng 合成结果的路径及名称
* @param width 结果图片的宽
* @param height 结果图片的高
*/
private static void overlapSmall(String srcPng, String outPng, int width, int height) {
try {
File srcFile = new File(srcPng);
Image bg_src = javax.imageio.ImageIO.read(srcFile);

int src_width = bg_src.getWidth(null);
int src_height = bg_src.getHeight(null);
BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

Graphics2D g2d = tag.createGraphics();

int row = 0;
int column = 0;
if(0 == width%src_width){
column = width/src_width;
}else{
column = width/src_width + 1;
}
if(0 == height%src_height){
row = height/src_height;
}else{
row = height/src_height + 1;
}

//g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 1.0f)); // 透明度设置
int x = 0;
int y = 0;
for(int i = 0; i < column; ++i){
y = 0;
for (int j = 0; j < row; ++j) {
g2d.drawImage(bg_src, x, y, src_width, src_height, null);
y += src_width;
}
x += src_height;
}
//g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER)); // 透明度设置 结束

FileOutputStream out = new FileOutputStream(outPng);
ImageIO.write(tag, "png", out);// 写图片
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}

android 平台测试成功

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
private static Bitmap overlapSmallToBitmap(Context context, int srcPng, int width, int height) {
Bitmap bitmap = null;
try {
InputStream is = context.getResources().openRawResource(srcPng);
Bitmap bg_src = BitmapFactory.decodeStream(is);

int src_width = bg_src.getWidth();
int src_height = bg_src.getHeight();

bitmap = Bitmap.createBitmap(width, height, bg_src.getConfig());
Canvas canvas = new Canvas(bitmap);
// Paint paint = new Paint();
// paint.setColor(Color.BLACK);
// paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DARKEN));

int row = 0;
int column = 0;
if(0 == width%src_width){
column = width/src_width;
}else{
column = width/src_width + 1;
}
if(0 == height%src_height){
row = height/src_height;
}else{
row = height/src_height + 1;
}

int x = 0;
int y = 0;
for(int i = 0; i < column; ++i){
y = 0;
for (int j = 0; j < row; ++j) {
canvas.drawBitmap(bg_src, x, y, null);
y += src_width;
}

x += src_height;
}
} catch (Exception e) {
e.printStackTrace();
}

return (bitmap);
}