JAVA

 public class ImageOperation {

	
	/**
	 * 将数据写入文件
	 * 
	 * @param data
	 *            byte[]
	 * @throws IOException
	 */
	public static void writeFile(byte[] data, String filename)
			throws IOException {
		File file = new File(filename);
		file.getParentFile().mkdirs();
		BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(file));
		bufferedOutputStream.write(data);
		bufferedOutputStream.close();
	}
	
	/**
	 * 读取文件
	 * @param id
	 * @param filePath
	 * @return
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	public static byte [] getImageBytes(long id,String filePath) throws FileNotFoundException,IOException{
        InputStream in = null;
        int len = 0;
        byte []  imageData = null;
        byte[] tmp = new byte[1024];
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
		in = new FileInputStream(filePath);
		while((len = in.read(tmp)) != -1){
		      buffer.write(tmp,0,len);
		}
		imageData = buffer.toByteArray();
		in.close();
        return imageData;
   }
	
   /**
    * 缩略图片<br>
    * @param file 源文件
    * @param height 目标高度
    * @param weight 目标宽度
    * @param fileTarget 缩略图存放地址
    * @return
    * @throws FileNotFoundException
    * @throws IOException
    */
   public static byte [] generateImage(File file,int height,int weight,File fileTarget) throws FileNotFoundException, IOException{
		BufferedImage img = ImageIO.read(file);
		int h = img.getHeight();
		int w = img.getWidth();
		
		byte [] imageThumbnail = null;
		if(h >= height && w >= weight){
			int nw = weight;
            int nh = (nw * h) / w;
            if(nh > height) {
                nh = height;
                nw = (nh * w) / h;
            }
            
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            BufferedImage dest = new BufferedImage(nw, nh,BufferedImage.TYPE_4BYTE_ABGR);
			dest.getGraphics().drawImage(img,0,0,nw, nh,null);
			GifEncoder.encode(dest, out);
			imageThumbnail = out.toByteArray();
		}else{
			imageThumbnail = getImageBytes(0,file.getPath());
		}
		//生成缩略图
		writeFile(imageThumbnail,fileTarget.getPath());
		return imageThumbnail;
	}
	
}
 

你可能感兴趣的:(File,writefile,imageoperation)