`
rekoe.net
  • 浏览: 8528 次
  • 性别: Icon_minigender_1
  • 来自: 北京
文章分类
社区版块
存档分类
最新评论

ImageUtil

阅读更多
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontFormatException;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.imageio.ImageIO;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

public class ImageUtil {
	private static String[] imageFormatArray = new String[] { ".jpg",".gif", ".png", ".bmp",".jpeg"};
	public static String createWaterMarkWithImage(String srcImgPath,String outputImage, String waterMarkImgPath,String zone,float transparency,float imageQuality,int watermarkMinWidth, int watermarkMinHeight) throws IOException {
		transparency /= 100;
		imageQuality /= 100;
		String srcType = verifyImageFormat(srcImgPath);
		if (srcType == null||verifyImageFormat(waterMarkImgPath)==null) {
			return "img_notype";
		}
		if((srcType.equals("gif")||srcType.equals("jpg"))&&isCattoon(srcImgPath)){
			return "img_isflash";
		}
		FileInputStream srcFis =new FileInputStream(srcImgPath);
		Image src_image = ImageIO.read(srcFis); 
		srcFis.close();
		int width = src_image.getWidth(null);
		int height = src_image.getHeight(null);
		if(width<watermarkMinWidth||height<watermarkMinHeight){
			return "img_mack_nofinish\t"+width + "\t"+ height;
		}		
		BufferedImage bufferedImage = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);
		Graphics graphics=bufferedImage.getGraphics();
		graphics.drawImage(src_image, 0, 0, null);
		src_image.flush();
		src_image=null;
		FileInputStream waterMarkFis =new FileInputStream(waterMarkImgPath);
		Image watermark_image = ImageIO.read(waterMarkFis); 
		waterMarkFis.close();
		int waterMarkImgWidth = watermark_image.getWidth(null);
		int waterMarkImgHeight = watermark_image.getHeight(null);
		if(width<waterMarkImgWidth||height<waterMarkImgHeight){
			return "img_mackimg_less";
		}
		int zoneArray[] = getWriteZoneForImage(zone, width, height, waterMarkImgWidth,waterMarkImgHeight);
		graphics.drawImage(watermark_image, zoneArray[0], zoneArray[1],waterMarkImgWidth, waterMarkImgHeight, null, null);
		graphics.dispose();
		watermark_image.flush();
		watermark_image=null;
		try {
			FileOutputStream out = new FileOutputStream(outputImage);
			JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
			JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bufferedImage);
			param.setQuality(imageQuality, true);
			encoder.encode(bufferedImage, param);
			out.close();
			bufferedImage.flush();
			bufferedImage = null;
			param=null;
			encoder=null;
		} catch (Exception e) {
			return e.getMessage();
		}
		return null;
	}
	public static String createWaterMarkWithCharacter(String srcImagePath, String outputImagePath,int watermarkminwidth,
			String watermarktext_text,String watermarktext_fontpath,int watermarktext_size,
			int watermarktext_angleInt,String watermarktext_color,int watermarktext_shadowx,
			int watermarktext_shadowy,String watermarktext_shadowcolor,String watermarktext_translatex,
			String watermarktext_translatey,String watermarktext_skewx,String watermarktext_skewy,
			float imageQuality,String watermarkstatus,float watermarktrans) 
			throws IOException {
		watermarktrans /= 100;
		imageQuality /= 100;
		float watermarktext_angle = (float)watermarktext_angleInt/100;
		String srcType = verifyImageFormat(srcImagePath);
		if (srcType == null) {
			return "img_notype";
		}
		if((srcType.equals("gif")||srcType.equals("jpg"))&&isCattoon(srcImagePath)){
			return "img_isflash";
		}
		FileInputStream srcFis =new FileInputStream(srcImagePath);
		Image src_image = ImageIO.read(srcFis); 
		srcFis.close();
		int width = src_image.getWidth(null);
		int height = src_image.getHeight(null);
		if(width<watermarkminwidth){
			return "img_mack_nofinish\t"+ width + "\t"+ height;
		}
		BufferedImage bimage = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);
		Graphics2D graphics2D = bimage.createGraphics();
		graphics2D.drawImage(src_image, 0, 0, null); 
		src_image.flush();
		src_image=null;
		
		Font font=null;
		FileInputStream fis=new FileInputStream(watermarktext_fontpath);
		try {
			font = Font.createFont(Font.TRUETYPE_FONT,fis);
		} catch (FontFormatException e1) {
			return "img_mack_nofont";
		}finally{
			fis.close();
		}
		font = font.deriveFont((float)watermarktext_size);		
		int textWidth = graphics2D.getFontMetrics(font).stringWidth(watermarktext_text);
		int textHeigth = graphics2D.getFontMetrics(font).getHeight();
		int zoneArray[] = getWriteZoneForCharacter(watermarkstatus, width, height, textWidth, textHeigth);
		graphics2D.rotate(watermarktext_angle); 
		graphics2D.setFont(font);
		graphics2D.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,watermarktrans));
		if(watermarktext_shadowcolor!=null&&!watermarktext_shadowcolor.trim().equals("")){
			try{
				graphics2D.setColor(Color.decode(watermarktext_shadowcolor));
			}catch(NumberFormatException exception){
				return "img_mack_shadow";
			}
			graphics2D.drawString(watermarktext_text, zoneArray[0]+watermarktext_shadowx, zoneArray[1]+watermarktext_shadowy); 
		}
		try{
			graphics2D.setColor(Color.decode(watermarktext_color));
		}catch(NumberFormatException exception){
			return "img_mack_color";
		}
		graphics2D.drawString(watermarktext_text, zoneArray[0], zoneArray[1]);  
		graphics2D.dispose();
		try {
			FileOutputStream out = new FileOutputStream(outputImagePath);
			JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
			JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bimage);
			param.setQuality(imageQuality, true);
			encoder.encode(bimage, param);
			bimage.flush();
			out.close();
			graphics2D=null;
			bimage=null;
			param=null;
			encoder=null;			
		} catch (Exception e) {
			return e.getMessage();
		}
		return null;
	}

	private static String verifyImageFormat(String fileName) {
		String result = null;		
		String fileType = fileName.substring(fileName.lastIndexOf(".")).toLowerCase();		
		for (String imageType:imageFormatArray) {
			if (fileType.equals(imageType)) {
				result = fileType.substring(1);
				break;
			}
		}
		return result;
	}	
	private static int[] getWriteZoneForImage(String zone, int width, int height,int waterMarkImgWidth, int waterMarkImgHeight) {
		int distance = 5;
		int[] zoneArray = new int[2];
		if ("1".equals(zone)) {
			zoneArray[0] = distance;
			zoneArray[1] = distance;
		}
		if ("2".equals(zone)) {
			zoneArray[0] = (width - waterMarkImgWidth) / 2;
			zoneArray[1] = distance;
		}
		if ("3".equals(zone)) {
			zoneArray[0] = width - distance - waterMarkImgWidth;
			zoneArray[1] = distance;
		}
		if ("4".equals(zone)) {
			zoneArray[0] = distance;
			zoneArray[1] = (height - waterMarkImgHeight) / 2;
		}
		if ("5".equals(zone)) {
			zoneArray[0] = (width - waterMarkImgWidth) / 2;
			zoneArray[1] = (height - waterMarkImgHeight) / 2;
		}
		if ("6".equals(zone)) {
			zoneArray[0] = width - distance - waterMarkImgWidth;
			zoneArray[1] = (height - waterMarkImgHeight) / 2;
		}
		if ("7".equals(zone)) {
			zoneArray[0] = distance;
			zoneArray[1] = height - distance - waterMarkImgHeight;
		}
		if ("8".equals(zone)) {
			zoneArray[0] = (width - waterMarkImgWidth) / 2;
			zoneArray[1] = height - distance - waterMarkImgHeight;
		}
		if ("9".equals(zone)) {
			zoneArray[0] = width - distance - waterMarkImgWidth;
			zoneArray[1] = height - distance - waterMarkImgHeight;
		}
		if ("isRandom".equals(zone)) {
			zoneArray[0] = (int) ((Math.random() * 1000) + 1)% (width - waterMarkImgWidth);
			zoneArray[1] = (int) ((Math.random() * 1000) + 1)% (height - waterMarkImgHeight);
		}
		return zoneArray;
	}
	private static int[] getWriteZoneForCharacter(String zone, int width, int height,int textWidth, int textHeigth) {
		int distance = 15;
		int[] zoneArray = new int[2];

		if ("1".equals(zone)) {
			zoneArray[0] = distance;
			zoneArray[1] = textHeigth;
		}
		if ("2".equals(zone)) {
			zoneArray[0] = (width - textWidth) / 2;
			zoneArray[1] = textHeigth;
		}
		if ("3".equals(zone)) {
			zoneArray[0] = width  - textWidth- distance;
			zoneArray[1] = textHeigth;
		}
		if ("4".equals(zone)) {
			zoneArray[0] = distance;
			zoneArray[1] = height /2+textHeigth/4;
		}
		if ("5".equals(zone)) {
			zoneArray[0] = (width - textWidth) / 2;
			zoneArray[1] = height /2+textHeigth/4;
		}
		if ("6".equals(zone)) {
			zoneArray[0] = width  - textWidth- distance;
			zoneArray[1] = height /2+textHeigth/4;
		}
		if ("7".equals(zone)) {
			zoneArray[0] = distance;
			zoneArray[1] = height  - distance;
		}
		if ("8".equals(zone)) {
			zoneArray[0] = (width - textWidth) / 2;
			zoneArray[1] = height  - distance;
		}
		if ("9".equals(zone)) {
			zoneArray[0] = width  - textWidth- distance;
			zoneArray[1] = height  - distance;
		}
		if ("isRandom".equals(zone)) {
			zoneArray[0] = (int) ((Math.random() * 1000) + 1)% (width - textWidth);
			zoneArray[1] = (int) ((Math.random() * 1000) + 1)% (height - textHeigth);
		}
		return zoneArray;
	}
	public static String createZoomImage(String sourceFilePath,String targetFileName,int width,int height) throws IOException{
		String fileType = verifyImageFormat(sourceFilePath);
		if(fileType==null){
			return "img_notype";
		}
		if((fileType.equals("gif")||fileType.equals("jpg"))&&isCattoon(sourceFilePath)){
			return "img_isflash";
		}
		FileInputStream fis =new FileInputStream(sourceFilePath);  
		Image src_image = ImageIO.read(fis); 
		fis.close();
		double oldHeight=src_image.getHeight(null);
		double oldWidth=src_image.getWidth(null);
		if (oldHeight > height ||oldWidth > width) {
			double ratio = 0;
			if (oldHeight > oldWidth) {
				ratio = (double)height /oldHeight;
			}
			else{
				ratio =(double)width /oldWidth;
			}
			if(ratio>1){
				ratio=1;
			}
			width=(int)(oldWidth*ratio);
			height=(int)(oldHeight*ratio);
			BufferedImage bufferedImage = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
			Graphics graphics = bufferedImage.createGraphics();
			graphics.drawImage(src_image, 0,0, width,height,null);
			graphics.dispose();			
			FileOutputStream fos = new FileOutputStream(targetFileName);
			JPEGImageEncoder jpg_encoder = JPEGCodec.createJPEGEncoder(fos);
			jpg_encoder.encode(bufferedImage); 
			src_image.flush();
			src_image = null;
			fos.close();
			graphics=null;
			fos=null;
			bufferedImage.flush();
			bufferedImage=null;
			jpg_encoder=null;
			return null;
		}else{
			return "img_thumb_nofinish\t"+ width + "\t"+ height;
		}
	}
	
	private static boolean isCattoon(String srcImgPath) throws IOException{
		FileInputStream srcFis =new FileInputStream(srcImgPath);
		int log = 0;
		int currentByte = 0;
		while((currentByte = srcFis.read())!=-1){
			if(log == 0 && currentByte == 0x21
					||log == 1 && currentByte == 0xff
					||log == 2 && currentByte == 0x0b
					||log == 3 && currentByte == 'N'
					||log == 4 && currentByte == 'E'
					||log == 5 && currentByte == 'T'
					||log == 6 && currentByte == 'S'
					||log == 7 && currentByte == 'C'
					||log == 8 && currentByte == 'A'
					||log == 9 && currentByte == 'P'
					||log == 10 && currentByte == 'E'
					||log == 11 && currentByte == '2'
					||log == 12 && currentByte == '.'
					||log == 13 && currentByte == '0'){
				log++;
				continue;
			}
			if(log==14){
				break;
			}
			log = 0;
		}
		srcFis.close();
		return log == 14;
	}
}


处理图片大小
分享到:
评论

相关推荐

    应用ImageUtil进行图片压缩(源代码)

    在这个场景中,我们关注的是使用一个名为`ImageUtil`的工具类来实现图片的压缩并生成缩略图。下面将详细解释如何使用`ImageUtil`进行图片压缩以及相关的编程知识点。 首先,`ImageUtil`通常是一个自定义的Java库...

    ImageUtil 图片渲染第三方类

    ImageUtil是一个第三方图片渲染库,它为开发者提供了便捷的方式来处理和操作图片,特别是对于那些需要快速实现多种图片效果的应用来说,ImageUtil是一个非常实用的工具。 ImageUtil的核心功能在于其内置了13种不同...

    ImageUtil 图片高保真缩放与裁剪,不依赖于任何第三方库

    然而,`ImageUtil`是一个特别的工具类,它实现了图片的高保真缩放和裁剪功能,而且不依赖任何第三方库,这意味着我们可以直接在项目中使用这个类,而不需要引入额外的依赖,这对于保持项目的轻量化和减少潜在的冲突...

    Android imageUtil 裁剪

    `imageUtil`裁剪工具类是为了简化这一过程而设计的。这个工具类是基于第三方开源库进行修改和优化的,目的是为了提供更加高效、易用的图片裁剪功能。下面我们将详细讨论Android图片裁剪的基本原理和`imageUtil`裁剪...

    android图片Imageutil

    ### 图片工具类(ImageUtil)知识点详解 #### 一、概述 在Android开发过程中,对图片的处理是一项常见的任务,包括但不限于保存图片到本地、从网络加载图片等操作。本篇将详细介绍一个实用的图片工具类`ImageUtil`,...

    ImageUtil.java

    本文件是图片验证码工具类,作用是生成一个四位数的图片验证码

    ImageUtil.rar

    这个名为"ImageUtil.rar"的压缩包文件提供了一个专门用于给图片添加水印的工具类。下面我们将深入探讨这个工具类的可能实现以及相关的编程知识点。 首先,`ImageUtil.java`是这个工具类的核心文件。在Java中,处理...

    ImageUtil.rar_Java编程_Java_

    这个过程可以被封装在一个名为`ImageUtil`的类中,就像压缩包中的`ImageUtil`文件一样。 数据库操作通常涉及到JDBC(Java Database Connectivity),它是Java平台的标准接口,用于连接各种数据库。在将16进制数据...

    安卓java读取网页源码-ImageUtil:基于OpenCVAndroid图像处理工具软件

    ImageUtil 基于OpenCVAndroid图像处理工具软件。本项目采用Android Studio开发安卓APP,使用C++(OpenCV)编写图片处理算法。主要处理图片的对比度,饱和度以及对图片进行一定程度的清晰度增强。 在网上找了许多关于...

    ImageUtil.zip_android开发_Java__android开发_Java_

    "ImageUtil.zip"这个压缩包提供了一个名为"ImageUtil.java"的工具类,专门用于处理通过camera2 API获取的相机数据,并将其转化为可以使用MediaCodec编码为H264格式的工具。以下是对这个知识点的详细解释: 1. **...

    ImageUtil: 图片和字节数组相互转换、图片保存工具类

    Android 图片和字节数组相互转换、图片保存工具类

    imageUtil.txt

    将 图片背景处理成透明

    imageutil.js

    解决uniapp图片上传时图片旋转90度问题。

    ImageUtil.jar

    本jar包可以将本地图片转成base64数据格式,下载后直接放在jmeter目录下lib文件夹中,在beanshell里引用

    Android代码-Util

    ImageUtil.getImageFromAlbum(UploadFileActivity.this); ImageUtil.getImageFromCamera(UploadFileActivity.this); ImageUtil.compress(); TimeTransform 时间戳格式转换类 &gt;在Android开发中常常会用到时间戳转换成...

Global site tag (gtag.js) - Google Analytics