JAVA图片处理工具类, 生成缩略图,给图片添加图片、文字水印,可设置大小、位置、透明度

/*******************************************************************************
 * Description: 图片水印工具类
 * 
 * @author xcwc1995
 * @version 1.0
 */
public class ImageRemarkUtil {
 
    // 水印透明度
    private static float alpha = 1f;
    // 水印横向位置
    private static int positionWidth = 0;
    // 水印纵向位置
    private static int positionHeight = 0;

private static Boolean DEFAULT_FORCE = false;

public static void thumbnailImage(InputStream imgFile, String fileName, OutputStream os) throws IOException{
   ImageUtils.thumbnailImage(imgFile, fileName, os, 320, 240, true);
}

/**
 * <p>Description: 根据图片路径生成缩略图 </p>
 * @param imgFile    原图片流
 * @param fileName    原图片名称
 * @param os       输出流
 * @param w            缩略图宽
 * @param h            缩略图高
 * @param prevfix    生成缩略图的前缀
 * @param force        是否强制按照宽高生成缩略图(如果为false,则生成最佳比例缩略图)
 */
public static void thumbnailImage(InputStream imgFile, String fileName, OutputStream os, int w, int h, boolean force) throws IOException {
    if(imgFile != null){
        try {
            // ImageIO 支持的图片类型 : [BMP, bmp, jpg, JPG, wbmp, jpeg, png, PNG, JPEG, WBMP, GIF, gif]
            String types = Arrays.toString(ImageIO.getReaderFormatNames());
            String suffix = null;
            // 获取图片后缀
            if (fileName == null){
               fileName = "test.png";
            }
            if(fileName.indexOf(".") > -1) {
                suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
            }// 类型和图片后缀全部小写,然后判断后缀是否合法
            if(suffix == null || types.toLowerCase().indexOf(suffix.toLowerCase()) < 0){
                LogUtils.error("Sorry, the image suffix is illegal. the standard image suffix is {}." + types);
                return;
            }
            Image img = ImageIO.read(imgFile);
            if(!force){
                // 根据原图与要求的缩略图比例,找到最合适的缩略图比例
                int width = img.getWidth(null);
                int height = img.getHeight(null);
                if((width*1.0)/w < (height*1.0)/h){
                    if(width > w){
                        h = Integer.parseInt(new java.text.DecimalFormat("0").format(height * w/(width*1.0)));
                    }
                } else {
                    if(height > h){
                        w = Integer.parseInt(new java.text.DecimalFormat("0").format(width * h/(height*1.0)));
                    }
                }
            }
            BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
            Graphics g = bi.getGraphics();
            g.drawImage(img, 0, 0, w, h, Color.LIGHT_GRAY, null);
            g.dispose();
            //String p = imgFile.getPath();
            // 将图片保存在原目录并加上前缀
            //ImageIO.write(bi, suffix, new File(p.substring(0,p.lastIndexOf(File.separator)) + File.separator + prevfix +imgFile.getName()));
            ImageIO.write(bi, suffix, os);
        } catch (IOException e) {
           LogUtils.error("generate thumbnail image failed.",e);
        }
    }else{
        LogUtils.warn("the image is not exist.");
    }

}

/**
 * <p>Description: 根据图片路径生成缩略图 </p>
 * @param imagePath    原图片路径
 * @param w            缩略图宽
 * @param h            缩略图高
 * @param prevfix    生成缩略图的前缀
 * @param force        是否强制按照宽高生成缩略图(如果为false,则生成最佳比例缩略图)
 */
public static ByteArrayOutputStream thumbnailImage(File imgFile, int w, int h, boolean force){
    if(imgFile.exists()){
        try {
            // ImageIO 支持的图片类型 : [BMP, bmp, jpg, JPG, wbmp, jpeg, png, PNG, JPEG, WBMP, GIF, gif]
            String types = Arrays.toString(ImageIO.getReaderFormatNames());
            String suffix = null;
            // 获取图片后缀
            if(imgFile.getName().indexOf(".") > -1) {
                suffix = imgFile.getName().substring(imgFile.getName().lastIndexOf(".") + 1);
            }// 类型和图片后缀全部小写,然后判断后缀是否合法
            if(suffix == null || types.toLowerCase().indexOf(suffix.toLowerCase()) < 0){
                LogUtils.error("Sorry, the image suffix is illegal. the standard image suffix is {}." + types);
                return null;
            }
            Image img = ImageIO.read(imgFile);
            if(!force){
                // 根据原图与要求的缩略图比例,找到最合适的缩略图比例
                int width = img.getWidth(null);
                int height = img.getHeight(null);
                if((width*1.0)/w < (height*1.0)/h){
                    if(width > w){
                        h = Integer.parseInt(new java.text.DecimalFormat("0").format(height * w/(width*1.0)));
                    }
                } else {
                    if(height > h){
                        w = Integer.parseInt(new java.text.DecimalFormat("0").format(width * h/(height*1.0)));
                    }
                }
            }
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
            Graphics g = bi.getGraphics();
            g.drawImage(img, 0, 0, w, h, Color.LIGHT_GRAY, null);
            g.dispose();
            //String p = imgFile.getPath();
            // 将图片保存在原目录并加上前缀
            //ImageIO.write(bi, suffix, new File(p.substring(0,p.lastIndexOf(File.separator)) + File.separator + prevfix +imgFile.getName()));
            ImageIO.write(bi, suffix, out);

            return out;
        } catch (IOException e) {
           LogUtils.error("generate thumbnail image failed.",e);
           return null;
        }
    }else{
        LogUtils.warn("the image is not exist.");
        return null;
    }
}

/**
 * <p>Description: 根据图片路径生成缩略图 </p>
 * @param imagePath    原图片路径
 * @param w            缩略图宽
 * @param h            缩略图高
 * @param prevfix    生成缩略图的前缀
 * @param force        是否强制按照宽高生成缩略图(如果为false,则生成最佳比例缩略图)
 */
public static ByteArrayOutputStream thumbnailImage(String imagePath, int w, int h, boolean force){
    File imgFile = new File(imagePath);
    return thumbnailImage(imgFile, w, h, force);
}


/**
 * <p>Description: 根据图片路径生成默认尺寸缩略图 </p>
 * @param imagePath    原图片路径
 * @param w            缩略图宽
 * @param h            缩略图高
 * @param prevfix    生成缩略图的前缀
 */
public static ByteArrayOutputStream thumbnailImage(String imagePath, int w, int h){
    File imgFile = new File(imagePath);
    return thumbnailImage(imgFile, w, h, DEFAULT_FORCE);
}

 
    /**
     * 
     * @param alpha
     *            水印透明度
     * @param positionWidth
     *            水印横向位置
     * @param positionHeight
     *            水印纵向位置
     */
    public static void setImageMarkOptions(float alpha, int positionWidth,
            int positionHeight, Font font, Color color) {
        if (alpha != 0.0f)
            ImageRemarkUtil.alpha = alpha;
        if (positionWidth != 0)
            ImageRemarkUtil.positionWidth = positionWidth;
        if (positionHeight != 0)
            ImageRemarkUtil.positionHeight = positionHeight;
    }
 
    /**
     * 给图片添加水印图片
     * 
     * @param iconPath
     *            水印图片路径
     * @param srcImgPath
     *            源图片路径
     * @param targerPath
     *            目标图片路径
     * @param height
     * @param width
     */
//    public static void markImageByIcon(String iconPath, String srcImgPath,
//            String targerPath,String watermarkPosition,int width, int height) {
//        markImageByIcon(iconPath, srcImgPath, targerPath,watermarkPosition,width, height);
//    }
 
    /**
     * 给图片添加水印图片、可设置水印图片旋转角度
     * 
     * @param iconPath
     *            水印图片路径
     * @param srcImgPath
     *            源图片路径
     * @param targerPath
     *            目标图片路径
     * @param degree
     *            水印图片旋转角度
     * @param markAlpha 
     */
    public static void markImageByIcon(String iconPath, String srcImgPath,
            String targerPath, Integer degree, String watermarkPosition,float markAlpha, int width, int height) {
        OutputStream os = null;
        try {
 
            Image srcImg = ImageIO.read(new File(srcImgPath));
 
            BufferedImage buffImg = new BufferedImage(srcImg.getWidth(null),
                    srcImg.getHeight(null), BufferedImage.TYPE_INT_RGB);
            int srcWidth=srcImg.getWidth(null);
            int srcHeight=srcImg.getHeight(null);
            // 1、得到画笔对象
            Graphics2D g = buffImg.createGraphics();
 
            // 2、设置对线段的锯齿状边缘处理
            g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                    RenderingHints.VALUE_INTERPOLATION_BILINEAR);
 
            g.drawImage(
                    srcImg.getScaledInstance(srcImg.getWidth(null),
                            srcImg.getHeight(null), Image.SCALE_SMOOTH), 0, 0,null);
            
            // 3、设置水印旋转
            if (null != degree) {
                g.rotate(Math.toRadians(degree),
                        (double) buffImg.getWidth() / 2,
                        (double) buffImg.getHeight() / 2);
            }
            // 4、水印图片的路径 水印图片一般为gif或者png的,这样可设置透明度
            ImageIcon imgIcon = new ImageIcon(iconPath);
            // 5、得到Image对象。
            Image img = imgIcon.getImage();
            int watermarkImageWidth=img.getWidth(null);
            int watermarkImageHeight=img.getHeight(null);
            double dmarkWidth = width*0.4;// 设置水印的宽度为图片宽度的0.4倍
            double dmarkHeight = dmarkWidth * ((double)watermarkImageHeight/(double)watermarkImageWidth);//强转为double计算宽高比例
            int imarkWidth = (int) dmarkWidth;
            int imarkHeight = (int) dmarkHeight;
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,    markAlpha));
            // 6、水印图片的位置
            int x;
            int y;
            switch (watermarkPosition) {
            case "topLeft":
                x = 0;
                y = 0;
                break;
            case "topRight":
                x = srcWidth - imarkWidth;
                y = 0;
                break;
            case "topCenter":
                x = (srcWidth - imarkWidth) / 2;
                y = 0;
                break;
            case "center":
                x = (srcWidth - imarkWidth) / 2;
                y = (srcHeight - imarkHeight) / 2;
                break;
            case "centerLeft":
                x = 0;
                y = (srcHeight - imarkHeight) / 2;
                break;
            case "centerRight":
                x = srcWidth - imarkWidth;
                y = (srcHeight - imarkHeight) / 2;
                break;
            case "bottomLeft":
                x = 0;
                y = srcHeight - imarkHeight;
                break;
            case "bottomCenter":
                x = (srcWidth - imarkWidth) / 2;
                y = srcHeight - imarkHeight;
                break;
            case "bottomRight":
                x = srcWidth - imarkWidth;
                y = srcHeight - imarkHeight;
                break;
            default:
                x = srcWidth - imarkWidth;
                y = srcHeight - imarkHeight;
                break;
            }
            
//            double dmarkWidth = width*0.4;// 设置水印的宽度为图片宽度的0.4倍
//            double dmarkHeight = dmarkWidth * ((double)watermarkImageHeight/(double)watermarkImageWidth);//强转为double计算宽高比例
//            int imarkWidth = (int) dmarkWidth;
//            int imarkHeight = (int) dmarkHeight;
            //positionWidth = (int) (width - dmarkWidth);
        //    positionHeight = (int) (height - dmarkHeight);
            
            
            
            g.drawImage(img, x, y, imarkWidth,    imarkHeight, null);
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
            // 7、释放资源
            g.dispose();
            // 8、生成图片
            os = new FileOutputStream(targerPath);
            ImageIO.write(buffImg, "JPG", os);
            System.out.println("图片完成添加水印图片");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != os)
                    os.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
 
    }

/**
    * 将InputStream写入本地文件
    * @param destination 写入本地目录
    * @param input 输入流
    * @throws IOException IOException
    */
   public static void writeToLocal(String destination, InputStream input)
           throws IOException {
       int index;
       byte[] bytes = new byte[1024];
       FileOutputStream downloadFile = new FileOutputStream(destination);
       while ((index = input.read(bytes)) != -1) {
           downloadFile.write(bytes, 0, index);
           downloadFile.flush();
       }
       input.close();
       downloadFile.close();

   }
/**
 * 添加文字水印
 * @param inputStream
 * @param imageType
 * @param textContent
 * @param font
 * @param color
 * @param x
 * @param y
 * @return
 */
public static InputStream addTextWaterMark(InputStream inputStream,String imageType,String textContent,Font font,Color color,int height,int padding) {
   InputStream outInputSteam = null;
   if(inputStream != null){
        try {
           ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

           Image srcImg = ImageIO.read(inputStream);
            int srcImgWidth = srcImg.getWidth(null);//获取图片的宽
            int srcImgHeight = srcImg.getHeight(null);//获取图片的高

            BufferedImage bufImg = new BufferedImage(srcImgWidth, srcImgHeight, BufferedImage.TYPE_INT_RGB);

            // 绘制图像
            Graphics2D g = bufImg.createGraphics();
         int x = srcImgWidth - getWatermarkLength(textContent, g) - padding;
         int y = srcImgHeight - padding - height;
            g.drawImage(srcImg, x, y, srcImgWidth, srcImgHeight, null);
         g.setFont(font);
            g.setColor(color);
            g.setFont(font);

            // 给图片加文字水印
            g.drawString(textContent, x, y );

            g.dispose();
            ImageIO.write(bufImg, imageType, outputStream);
            outInputSteam = new ByteArrayInputStream(outputStream.toByteArray());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return outInputSteam;
}

/**
 * 添加文字水印
 * @param inputStream
 * @param imageType
 * @param textContent
 * @param font
 * @param color
 * @param x
 * @param y
 * @return
 */
public static InputStream addTextWaterMark(String srcImagePath,String imageType,String textContent,Font font,Color color,int x,int y) {
   InputStream outInputSteam = null;
       try {

           ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

           Image srcImg = ImageIO.read(new File(srcImagePath));

           int srcImgWidth = srcImg.getWidth(null);//获取图片的宽
           int srcImgHeight = srcImg.getHeight(null);//获取图片的高

           BufferedImage bufImg = new BufferedImage(srcImgWidth, srcImgHeight, BufferedImage.TYPE_INT_RGB);

           // 绘制图像
           Graphics2D g = bufImg.createGraphics();

           g.drawImage(srcImg, 0, 0, srcImgWidth, srcImgHeight, null);
           g.setColor(color);
           g.setFont(font);

           // 给图片加文字水印
           g.drawString(textContent, x, y );

           g.dispose();
           ImageIO.write(bufImg, imageType, outputStream);
           outInputSteam = new ByteArrayInputStream(outputStream.toByteArray());
       } catch (Exception e) {
           e.printStackTrace();
       }
    return outInputSteam;
}

 

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值