ITeye博客

Java小程序:批量图片处理(缩小和添加Logo)

zeroliu · 2007-04-28 09:56 · Markdown

【虎.无名】喜欢写Blog,经常上传照片,问题是照片通常都太大,相册空间又太小,通常都要做一些压缩处理。虽然windows自带的画图工具也可以完成,但是需要手工一个一个完成,我又是比较懒的人,所以,写了下面一个小工具,把图片按比例缩小x倍,或者添加一个Logo文字,关键是能批量处理,省事多了。如果需要使用,得改改main,代码很简单,我就不写详细使用手册了。

import java.io.*;
import java.awt.*;
import java.awt.image.*;
import com.sun.image.codec.jpeg.*;
import javax.imageio.ImageIO;

public class JpgTest {
	public static void jpg_logo(String jpgName, String logoText)	throws Exception {
		File _file = new File(jpgName+".jpg");	//读入文件
		Image src = ImageIO.read(_file);	//构造Image对象
		int w0 = src.getWidth(null);		//得到源图宽
		int h0 = src.getHeight(null); 		//得到源图长
		int w2 = 800;	//=w0/2
		int h2 = 600;	//=h0/2
		int fontSize = 32;
		//缩小一 半为(800,600)
		BufferedImage tag = null;
		tag = new BufferedImage(w2, h2, BufferedImage.TYPE_INT_RGB);
		tag.getGraphics().drawImage(src, 0, 0,w2, h2, null);	//绘制缩小后的图
		//标注水印
	        Graphics g = tag.getGraphics();
		g.setColor(Color.RED);		//以下设置前景色BLACK
	//	g.setXORMode(Color.RED);
	        g.setFont(new Font("MyFont", Font.BOLD, fontSize));	//PLAIN,BOLD,ITALIC
	//	g.drawString(logoText, 10, 10+fontSize);
	        g.drawString(logoText, w2-fontSize*(logoText.length()+3)/2, h2-10);
	        g.dispose();
	        //保存文件,输出到文件流
	        FileOutputStream out = new FileOutputStream(jpgName+"_800.jpg");	
	        try {
			JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); 
			encoder.encode(tag); //近JPEG编码
			//System.out.print(width+"*"+h0); 
		}finally{
			out.close();
		}
	}
	public static void jpg_logo()	throws Exception {
		File _file = new File("test_old.jpg");	//读入文件
		Image src = ImageIO.read(_file);	//构造Image对象
		int w0=src.getWidth(null);		//得到源图宽
		int h0=src.getHeight(null); 	//得到源图长
		//缩小一半
		BufferedImage tag = null;
		tag = new BufferedImage(w0/2,h0/2,BufferedImage.TYPE_INT_RGB);
		tag.getGraphics().drawImage(src,0,0,w0/2,h0/2,null);	//绘制缩小后的图
		//标注水印
	        Graphics g = tag.getGraphics();
		//g.setColor(Color.BLACK);	 //以下设置前景色
	        g.setXORMode(Color.GREEN);
	        g.setFont(new Font("MyFont", Font.ITALIC, 24));
	        g.drawString("www.Test.com", w0/4, h0/4);
	        g.dispose();
	        //保存文件
	        FileOutputStream out = new FileOutputStream("test_new.jpg");	//输出到文件流
		JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); 
		encoder.encode(tag); //近JPEG编码
		//System.out.print(width+"*"+h0); 
		out.close();
	}
	public static void jpg_mini(String fn, int factor)	throws Exception {
		String	f0 = fn+".jpg";
		File	f = new File(f0);	//读入文件
		Image src = ImageIO.read(f);	//构造Image对象
		int w0 = src.getWidth(null);	//得到源图宽
		int h0 = src.getHeight(null); 	//得到源图长
		if (w0<800)	throw new Exception("w0<800");
		//-------------------------
		String	f2 = fn+"_.jpg";
		int w2 = w0 / factor;
		int h2 = h0 / factor;
		BufferedImage tag = new BufferedImage(w2, h2,BufferedImage.TYPE_INT_RGB);
		tag.getGraphics().drawImage(src, 0, 0, w2, h2, null);	//绘制缩小后的图
		System.out.println(f0+"("+w0+"*"+h0+") \t=> "+f2+"("+w2+"*"+h2+")");
	        //保存文件
	        FileOutputStream out = new FileOutputStream(f2);	//输出到文件流
		JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); 
		encoder.encode(tag); //近JPEG编码
		out.close();
	}
	public static void jpg_rename(String fn)	throws Exception {
		File	f0 = new File(fn+".jpg");
			f0.delete();
		File	f2 = new File(fn+"_.jpg");
			f2.renameTo(f0);
	}
	public static String zeroInt(int n, int len) {
		String	s = ""+n;
		for(int i=s.length(); i<len; i++) {
			s = '0'+s;
		}
		return	s;
	}
	public static void jpg_mini(int factor, String fx, int idx0, int idx2, int iLen)	throws Exception {
		//String fx = "D:/_拓展培训20060915/DSC_";
		//int idx0 = 624;
		//int idx2 = 656;	
		String fn = null;
		for(int i=idx0; i<=idx2; i++) {
			fn = fx + zeroInt(i, iLen);	//长度4 如:DSC_0168.JPG
			try {
				jpg_mini(fn, factor);
				jpg_rename(fn);
			}catch(Exception e){
				System.out.println(fn+"..."+e);
			}
		}
	}
	public static void main(String args[])	throws Exception {
	//	jpg_logo();
	//	jpg_mini("test_old");
		jpg_mini(4, "D:/_拓展培训20060915/DSC_", 1, 200, 4);	//缩小4倍(0001-0200)
	//	jpg_logo("P1010105", "2005-4-9");
	//	jpg_logo("P1010086", "2005-4-9");
	//	jpg_logo("P1010017", "2005-4-18");
	//	Font f1 = Font.decode("宋体");		//System.out.println(s);
	//	Font f2 = Font.getFont("宋体");		//System.out.println(s);
	}
}

评论(1)

  1. #1 楼 · zeroliu · 2012-04-13 15:50

    新的代码,有一个平滑压缩的处理,还有变灰的处理。

    
    
    import java.io.*;
    import java.awt.*;
    import java.awt.image.*;
    import java.awt.Graphics;
    import java.awt.color.ColorSpace;
    import javax.imageio.ImageIO;
    
    import com.sun.image.codec.jpeg.JPEGCodec;
    import com.sun.image.codec.jpeg.JPEGImageEncoder;
    /**
     * http://blog.csdn.net/novelly/article/details/4390050  JAVA图片处理放大缩小
     * http://www.diybl.com/course/3_program/java/javashl/20071126/87694.html
     * http://webcache.googleusercontent.com/search?q=cache:3vIkSKZAxnAJ:blog.csdn.net/a673341766/article/details/7288048+&cd=4&hl=zh-CN&ct=clnk
     * http://www.weste.net/2009/5-31/14581345808.html Java图片缩小后不失真的代码(缩略图) 
     * @author lius
     *
     */
    public class ImageScale {
        /** 缩放图像(针对整个目录)
         * @param srcImageFile 源图像文件目录
         * @param result       缩放后的图像地址
         * @param flag         缩放选择:true 放大; false 缩小;
         * @param scale        缩放比例
         */
        public static void doScales(String srcPath, String outPath, boolean flag, int scale) {
        	File path = new File(srcPath); 
        	File[] images = path.listFiles(new FilenameFilter() {
    			@Override public boolean accept(File dir, String name) {
    				name = name.toLowerCase();
    				if (name.endsWith(".jpg")) return true;
    				if (name.endsWith(".gif")) return true;
    				if (name.endsWith(".png")) return true;
    				return false;
    			}
        	});
        	for(int i=0; i<images.length; i++) {
        		File fin = images[i];
        		String name = fin.getName().replace('.', '_');
        		String fout = String.format("%s/%s-%d.jpg", outPath, name, scale);
        		if (new File(fout).exists()) {
            		System.out.println("E doScales("+i+")..."+fout+"...Exists");
        		}else {
        			doScale(fin, fout, flag, scale);
        			doScale2(fin, fout, flag, scale);//Java图片缩小后不失真的代码(缩略图) 
            		System.out.println("# doScales("+i+")..."+fout);
        		}
        	}
        }
        /** 缩放图像
         * @param srcImageFile 源图像文件地址
         * @param result       缩放后的图像地址
         * @param flag         缩放选择:true 放大; false 缩小;
         * @param scale        缩放比例
         */
        public static void doScale(String srcFile, String outFile, boolean flag, int scale) {
        	doScale(new File(srcFile), outFile, flag, scale);
        }
        public static void doScale(File srcFile, String outFile, boolean flag, int scale) {
            try{
                BufferedImage src = ImageIO.read(srcFile); // 读入文件
                int width = src.getWidth(); // 得到源图宽
                int height = src.getHeight(); // 得到源图长
                if (flag){//放大
                    width = width * scale;		height = height * scale;
                }else{		// 缩小
                    width = width / scale;		height = height / scale;
                }
                Image image = src.getScaledInstance(width, height, Image.SCALE_DEFAULT);
                BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
                Graphics g = tag.getGraphics();
                g.drawImage(image, 0, 0, null); // 绘制缩小后的图
                g.dispose();
                ImageIO.write(tag, "JPEG", new File(outFile));// 输出到文件流
            }catch (IOException e){
                e.printStackTrace();
            }
        }
        //Java图片缩小后不失真的代码(缩略图) 
        public static void doScale2(File fSrc, String imgDst, boolean flag, int scale) {
    		FileOutputStream fos = null;
    	    try {   //*Java图片缩小后不失真的代码(缩略图) 
    	        if (!fSrc.exists())	return;
                BufferedImage src = ImageIO.read(fSrc); // 读入文件
                int width = src.getWidth(); // 得到源图宽
                int height = src.getHeight(); // 得到源图长
                if (flag){//放大
                    width = width * scale;		height = height * scale;
                }else{		// 缩小
                    width = width / scale;		height = height / scale;
                }
    	        BufferedImage tag = new BufferedImage((int) width, (int) height, BufferedImage.TYPE_INT_RGB);
    	        tag.getGraphics().drawImage(src.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0,  null);   
    	        //tag.getGraphics().drawImage(src.getScaledInstance(width, height, Image.SCALE_AREA_AVERAGING), 0, 0,  null);   
    	        fos = new FileOutputStream(imgDst);   
    	        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(fos);   
    	        encoder.encode(tag);
    	    }catch (IOException ex) {   
    	    	ex.printStackTrace();   
    	    }finally{
    	    	if (fos!=null) try{ fos.flush(); fos.close(); }catch(Exception e){}
    	    }
    	}  
        /*** 图像切割
         * @param srcImageFile 源图像地址
         * @param descDir      切片目标文件夹
         * @param destWidth    目标切片宽度
         * @param destHeight   目标切片高度
         */
        public static void doCut(String srcImg, String descDir, int destWidth, int destHeight){
            Image img;
            ImageFilter cropFilter;
            try{
                BufferedImage bi = ImageIO.read(new File(srcImg));// 读取源图像
                int srcWidth = bi.getHeight(); // 源图宽度
                int srcHeight = bi.getWidth(); // 源图高度
                if (srcWidth > destWidth && srcHeight > destHeight){
                    Image image = bi.getScaledInstance(srcWidth, srcHeight, Image.SCALE_DEFAULT);
                    destWidth = 200; // 切片宽度
                    destHeight = 150; // 切片高度
                    int cols = 0; // 切片横向数量
                    int rows = 0; // 切片纵向数量
                    // 计算切片的横向和纵向数量
                    if (srcWidth % destWidth == 0){
                        cols = srcWidth / destWidth;
                    }else{
                        cols = (int) Math.floor(srcWidth / destWidth) + 1;
                    }
                    if (srcHeight % destHeight == 0){
                        rows = srcHeight / destHeight;
                    }else{
                        rows = (int) Math.floor(srcHeight / destHeight) + 1;
                    }
                    // 循环建立切片(改进的想法:是否可用多线程加快切割速度)
                    for (int i = 0; i < rows; i++){
                        for (int j = 0; j < cols; j++){
                            // 四个参数分别为图像起点坐标和宽高
                            // 即: CropImageFilter(int x,int y,int width,int height)
                            cropFilter = new CropImageFilter(j * 200, i * 150, destWidth, destHeight);
                            img = Toolkit.getDefaultToolkit().createImage(new FilteredImageSource(image.getSource(), cropFilter));
                            BufferedImage tag = new BufferedImage(destWidth, destHeight, BufferedImage.TYPE_INT_RGB);
                            Graphics g = tag.getGraphics();
                            g.drawImage(img, 0, 0, null); // 绘制缩小后的图
                            g.dispose();
                            // 输出为文件
                            ImageIO.write(tag, "JPEG", new File(descDir + "pre_map_" + i + "_" + j + ".jpg"));
                        }
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        /*** 图像类型转换JPG格式( GIF->JPG GIF->PNG PNG->JPG PNG->GIF(X))
         */
        public static void toJPG(String fsource, String fout){
            try{
                File f = new File(fsource);
                if (! f.exists())	return;
                BufferedImage src = ImageIO.read(f);
                ImageIO.write(src, "JPEG", new File(fout));
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        /**
         * 彩色转为黑白
         * @param source
         * @param result
         */
        public static void toGray(String source, String result){
            try{
                BufferedImage src = ImageIO.read(new File(source));
                //CS_CIEXYZ绿色,CS_LINEAR_RGB加大对比度,其他错误
                ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_GRAY);
                ColorConvertOp op = new ColorConvertOp(cs, null);
                src = op.filter(src, null);
                ImageIO.write(src, "JPEG", new File(result));
            }catch (IOException e){
                e.printStackTrace();
            }
        }
        public static void main(String[] args) {
        	String base = "F:/照片/20120403宾得K5";
            //doScale("D:/100CASIO/CIMG0001.JPG","C:/Documents and Settings/ibm/桌面/image.jpg",false,10);
        	//doScale(base+"IMGP0158.JPG", base+"IMGP0158_.JPG", false, 5);
        	//doScales(base, base+"/out", false, 2);
        	doScales(base, base+"/out2", false, 4);
        	//toGray(base+"/out/IMGP0173_JPG-4.jpg", base+"/out/IMGP0173_JPG-4-gray.jpg");
        }
    }
    
    

评论功能维护中,当前仅展示历史评论。