java图片增加马赛克

  • 粘贴即用 具体需要根据项目情况进行调整


粘贴即用 具体需要根据项目情况进行调整

借鉴了许多代码粘贴的 不是原创 只是代码的拼凑师

package com.ruoyi.hfiveinterface.util;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

import javax.imageio.ImageIO;

import org.springframework.stereotype.Service;


/**
 * 图片增加马赛克工具类
 */

@Service
public class PhototMosaicUtil {

    /**
     * 给图片指定位置打马赛克
     * @param filePath 图片位置
     * @param targetPath 打码后的图片保存位置,若为空则保存路径默认为原图片路径
     * @param x 图片要打码区域左上角的横坐标
     * @param y 图片要打码区域左上角的纵坐标
     * @param width 图片要打码区域的宽度
     * @param height 图片要打码区域的高度
     * @param mosaicSize 马赛克尺寸,即每个矩形的长宽
     * @return
     * @throws IOException
     */
    @SuppressWarnings("static-access")
    public static boolean mosaic(String filePath, String targetPath,
                                 int x, int y, int width, int height, int mosaicSize) throws IOException {
        //1. 初始化图像处理各变量
        if (!filePath.endsWith(".png") && !filePath.endsWith(".jpg") &&
                !filePath.endsWith(".gif")) {
            System.err.println("ImageUtil>>>文件名非法,不是正确的图片文件名");
            return false;
        }
        int index = filePath.lastIndexOf(".");
        String suffix = filePath.substring(index + 1);
        if (targetPath != null  && !targetPath.endsWith(suffix)) {
            System.err.println("ImageUtil>>>目标文件后缀应与源文件后缀一致");
            return false;
        }
        File file = new File(filePath);
        if (!file.isFile()) {
            System.err.println("ImageUtil>>>" + filePath + "不是一个文件!");
            return false;
        }
        BufferedImage bi = ImageIO.read(file); // 读取该图片
        BufferedImage spinImage = new BufferedImage(bi.getWidth(),
                bi.getHeight(), bi.TYPE_INT_RGB);
        if (bi.getWidth() < mosaicSize || bi.getHeight() < mosaicSize || mosaicSize <= 0) { // 马赛克格尺寸太大或太小
            System.err.println("马赛克尺寸设置不正确");
            return false;
        }

        //2. 设置各方向绘制的马赛克块个数
        int xcount = 0; // 方向绘制个数
        int ycount = 0; // y方向绘制个数
        if (width % mosaicSize == 0) {
            xcount = width / mosaicSize;
        } else {
            xcount = width / mosaicSize + 1;
        }
        if (height % mosaicSize == 0) {
            ycount = height / mosaicSize;
        } else {
            ycount = height / mosaicSize + 1;
        }

        //3. 绘制马赛克(绘制矩形并填充颜色)
        Graphics gs = spinImage.getGraphics();
        gs.drawImage(bi, 0, 0, null);
        int xTmp = x;
        int yTmp = y;
        for (int i = 0; i < xcount; i++) {
            for (int j = 0; j < ycount; j++) {
                //马赛克矩形格大小
                int mwidth = mosaicSize;
                int mheight = mosaicSize;
                if(i == xcount - 1){   //横向最后一个比较特殊,可能不够一个size
                    mwidth = width - xTmp;
                }
                if(j == ycount - 1){  //同理
                    mheight = height - yTmp;
                }
                //矩形颜色取中心像素点RGB值
                int centerX = xTmp;
                int centerY = yTmp;
                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(bi.getRGB(centerX, centerY));
                gs.setColor(color);
                gs.fillRect(xTmp, yTmp, mwidth, mheight);
                yTmp = yTmp + mosaicSize;// 计算下一个矩形的y坐标
            }
            yTmp = y;// 还原y坐标
            xTmp = xTmp + mosaicSize;// 计算x坐标
        }
        gs.dispose();
        if (targetPath == null )
            targetPath = filePath;
        File sf = new File(targetPath);
        ImageIO.write(spinImage, suffix, sf); // 保存图片
        return true;
    }

    public static boolean mosaic(String filePath, String targetPath,
                                 ImageArea area, int mosaicSize) throws IOException {
        return  mosaic(filePath, targetPath, area.getX(), area.getY(),
                area.getWidth(), area.getHeight(), mosaicSize);
    }

    //链接url下载图片
    /**
     * 功能描述:
     * @param:  urlList  图片url地址
     * @param:  path     下载到本地的路径
     */
    private static void downloadPicture(String urlList,String path) {

        try {
            URL url = new URL(urlList);
            DataInputStream dataInputStream = new DataInputStream(url.openStream());
            FileOutputStream fileOutputStream = new FileOutputStream(new File(path));
            ByteArrayOutputStream output = new ByteArrayOutputStream();

            byte[] buffer = new byte[1024];
            int length;

            while ((length = dataInputStream.read(buffer)) > 0) {
                output.write(buffer, 0, length);
            }
            fileOutputStream.write(output.toByteArray());
            dataInputStream.close();
            fileOutputStream.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static void deleteFile(File file){
        //判断文件不为null或文件目录存在
        if (file == null || !file.exists()){
            System.out.println("文件删除失败,请检查文件路径是否正确");
            return;
        }
        //取得这个目录下的所有子文件对象
        File[] files = file.listFiles();
        //遍历该目录下的文件对象
        for (File f: files){
            //打印文件名
            String name = file.getName();
            System.out.println(name + "文件夹已清空");
            //判断子目录是否存在子目录,如果是文件则删除
            if (f.isDirectory()){
                deleteFile(f);
            }else {
                f.delete();
            }
        }
        //删除空文件夹  for循环已经把上一层节点的目录清空。
        //file.delete();
    }


    /**
     * 测试 图片打马赛克
     * @param args
     * @throws IOException
     */

    public static void main(String[] args) throws IOException {
        long time = System.currentTimeMillis();
        System.out.println(time);

        //先清空下载本地文件夹
        File file = new File("D:\\subImgKouBei0917dowlond");//输入要删除文件目录的绝对路径
        deleteFile(file);

        //https路径存入 本地文件夹
        String url =
                "https://k2.autoimg.cn/koubeidfs/g4/M12/E7/36/480x360_1_q87_autohomecar__ChsFVmDcMmuAFEIAAAWSEQyzIJs599.jpg";
        String path="D:\\subImgKouBei0917dowlond\\"+time+".jpg";
        downloadPicture(url,path);

        //再清空本地的 图片增加马赛克文件夹
        File file2 = new File("D:\\subImgKouBei0917");//输入要删除文件目录的绝对路径
        deleteFile(file2);

        //获取下载的图片的 宽度和高度 用于计算增加马赛克的位置
        File image=new File("D:\\subImgKouBei0917dowlond\\"+time+".jpg");
        BufferedImage localImg = ImageIO.read(new FileInputStream(image));
        int width=localImg.getWidth();
        int height=localImg.getHeight();


        //图片右下角增加马赛克
        boolean successOrFail = mosaic("D:\\subImgKouBei0917dowlond\\"+time+".jpg",
                "D:\\subImgKouBei0917\\"+time+".jpg", new ImageArea(width-60, height-20, 70, 40), 20);
        if (successOrFail){
            System.out.println("图片增加马赛克成功");
        }else {
            System.out.println("图片增加马赛克失败");
        }

    }


    




}
package com.ruoyi.hfiveinterface.util;


import org.springframework.stereotype.Service;

/**
 * 图片区域类
 * @author hty
 *
 */
@Service
public class ImageArea {
    int x;	//指定区域左上角横坐标
    int y;	//指定区域左上角纵坐标
    int width;	//指定区域宽度
    int height;	//指定区域高度
    public ImageArea(int x, int y, int width, int height) {
        super();
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
    }
    public int getX() {
        return x;
    }
    public void setX(int x) {
        this.x = x;
    }
    public int getY() {
        return y;
    }
    public void setY(int y) {
        this.y = y;
    }
    public int getWidth() {
        return width;
    }
    public void setWidth(int width) {
        this.width = width;
    }
    public int getHeight() {
        return height;
    }
    public void setHeight(int height) {
        this.height = height;
    }
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + height;
        result = prime * result + width;
        result = prime * result + x;
        result = prime * result + y;
        return result;
    }
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        ImageArea other = (ImageArea) obj;
        if (height != other.height)
            return false;
        if (width != other.width)
            return false;
        if (x != other.x)
            return false;
        if (y != other.y)
            return false;
        return true;
    }

}