首页 > 代码库 > 图片打水印 缩放 以及输入流转换

图片打水印 缩放 以及输入流转换

图片打水印和缩放:

 public final static BufferedImage[] pressImage(InputStream srcImg, String waterImg,float alpha) throws IOException {
    	
    	 //File file = new File(targetImg);
        Image image = ImageIO.read(srcImg);
        int width = image.getWidth(null);
        int height = image.getHeight(null);
        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = bufferedImage.createGraphics();
        g.drawImage(image, 0, 0, width, height, null);
    
        Image waterImage = ImageIO.read(new File(waterImg));    // 水印文件
        
        int width_1 = waterImage.getWidth(null);
        int height_1 = waterImage.getHeight(null);
        g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));
        
        int div=(int) (0.1*width_1);
          
        for(int y=0,row=0;y<height;y+=height_1+div,row++)
        {
        	int x=0;
        	       	
            for(;x<width;x+=width_1+div)
            {              	
            	g.drawImage(waterImage, x, y, width_1, height_1, null); // 水印文件结束	                	
            }
        }             
        
        g.dispose();
        
        BufferedImage bufferedImage2=Thumbnails.of(bufferedImage).size(100, 100).asBufferedImage();
        
       
      
       return new BufferedImage[]{bufferedImage,bufferedImage2};
    	
    }

图片的缩放使用了Thumbnails这个工具,(其实它也可以用来打水印的,不过我还没有研究)

jar 包或者maven 请自行搜索

需要特别注意的是 Thumbnails 默认是按照等比例进行缩放的并且它的缩放规则是:

假设 把图片所放到 200*300

* 若图片横比200小,高比300小,不变
* 若图片横比200小,高比300大,高缩小到300,图片比例不变
* 若图片横比200大,高比300小,横缩小到200,图片比例不变
* 若图片横比200大,高比300大,图片按比例缩小,横为200或高为300

bufferInage转换 inputSteam

private InputStream getInputstreamFromBufferedImage(BufferedImage img) throws IOException{
		 	ByteArrayOutputStream bs =new ByteArrayOutputStream();
		 	ImageOutputStream imOut =ImageIO.createImageOutputStream(bs);
	        ImageIO.write(img,"jpg",imOut); //scaledImage1为BufferedImage,jpg为图像的类型
	        
	        InputStream is =new ByteArrayInputStream(bs.toByteArray());
	        return is;
		
	}



图片打水印 缩放 以及输入流转换