给图片指定位置打马赛克
package com.cn.eqz.test;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.imageio.ImageIO;
public class ImgMosaic {
/**
* 图像处理类.
*
* @author danyan
*
*/
public static void main(String[] args) throws Exception {
ImgMosaic imageObj = new ImgMosaic();
String srcImagePath = "e://10.jpg";
String imageFormat = "jpg";
String toPath = "e://point-002.jpg";
int x = 400;//x坐标(马赛克起点横向坐标)
int y = 500;//y坐标(马赛克起点纵向坐标)
int width = 666;//马赛克区域宽度
int height = 88;//马赛克区域高度
imageObj.mosaic(srcImagePath, x, y, width, height, imageFormat, toPath);
}
public void mosaic(String srcImagePath,int x,int y,int width,int height,String imageFormat,String toPath) throws IOException{
FileOutputStream fos = null;
int xx = x;
try {
//获取源图片
BufferedImage image = ImageIO.read(new File(srcImagePath));
//根据xy点坐标绘制连接线
Graphics2D g2d = image.createGraphics();
//填充一个矩形
int xcount = 0;
int ycount = 0;
if(width%4==0){
xcount = width/4;//计算需要横向填充多少个矩形
}else{
xcount = width/4 + 1;//如果不被整除+1
}
if(height%4==0){
ycount = height/4;//计算需要纵向填充多少个矩形
}else{
ycount = height/4 + 1;//如果不被整除+1
}
for(int j = 0;j<ycount;j++){
for(int i = 0;i<xcount;i++){
int mwidth = 4;
int mheight = 4;
if(i==xcount-1){ //横向最后一个比较特殊,可能不够一个size
mwidth = width-x;
}
if(j == ycount-1){ //同理
mheight =height-y;
}
int centerX = x;
int centerY = y;
if (mwidth % 2 == 0) {
centerX += mwidth / 2; //计算横向中心点
} else {
centerX += (mwidth - 1) / 2;
}
if (mheight % 2 == 0) {
centerY += mheight / 2; //计算纵向向中心点
} else {
centerY += (mheight - 1) / 2;
}
Color color = new Color(image.getRGB(centerX, centerY)); //获取中心点数据
g2d.setColor(color); //稀释
g2d.fillRect(x, y, 4, 4);
x = x+4;
}
y=y+4;
x = xx;
}
g2d.dispose();
fos = new FileOutputStream(toPath);
ImageIO.write(image, imageFormat, fos);
} catch (IOException e) {
e.printStackTrace();
}finally{
if(fos!=null){
fos.close();
}
}
}
}

浙公网安备 33010602011771号