java读写图片

package hequn.image;

import java.awt.image.BufferedImage;
import java.awt.image.Raster;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.imageio.ImageIO;



public class PackImage {
	static public void main(String[] args) throws IOException {
		File file = new File("C://Users//Administrator//Desktop//20//115//MSingle_0_115.png");
		InputStream in = null;
		in = new FileInputStream(file);
		BufferedImage inputImage = ImageIO.read(in);
		Raster raster = inputImage.getRaster();
		int LENGTH = 1024 * 768 * 3;
		int[] refdata = new int[LENGTH];
		int idx = 0, r, g, b, rgb;
		for(int i = inputImage.getMinX(); i < 1024; ++i) {
	    	for(int j = inputImage.getMinY(); j < 768; ++j) {
	    		Object rgbobj = inputImage.getRaster().getDataElements(i, j, null);
	    		r = inputImage.getColorModel().getRed(rgbobj);
	    		g = inputImage.getColorModel().getGreen(rgbobj);
	    		b = inputImage.getColorModel().getBlue(rgbobj);
	    		refdata[idx++] = b;
	    		refdata[idx++] = g;
	    		refdata[idx++] = r;
	    	 }
	     }
		
		
		BufferedImage outputImage = new BufferedImage(1024,768, 5);
		idx = 0;
		for (int i = 0; i < 1024; i++) {
			for (int j = 0; j < 768; j++) {
				b = refdata[idx];
				g = refdata[idx + 1];
				r = refdata[idx + 2];
				
				r = (r * 3 + g * 6 + b * 1) / 10;
				g = r;
				b = g;
				
				idx += 3;
				
				rgb = (r * 256 + g) * 256 + b;
				if (rgb > 8388608) {
					rgb = rgb - 16777216;
				}
				outputImage.setRGB(i, j, rgb);
			}
		}
		
		// Write the image to byte[]
		byte[] imageInByte;
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		ImageIO.write(outputImage, "png", baos);
		baos.flush();
		imageInByte = baos.toByteArray();
		baos.close();

		// Create output file
		FileOutputStream out = null;
		out = new FileOutputStream(new File("C://Users//Administrator//Desktop//20//115//add_MSingle_0_115.png"));
		for (int i = 0; i < imageInByte.length; ++i) {
			 out.write(imageInByte[i]);
		}

		// Close the file stream
		out.close();

	}
}

 

posted on 2013-12-18 15:45  hequn8128  阅读(262)  评论(0)    收藏  举报

导航