java实现图片转化为数据流

方法如下:

/**
	 * Copy file from inputStream
	 * 
	 * @param is
	 * @param f2
	 * @throws Exception
	 */
	public static void copyFileFromInputStream( InputStream is, File f2 ) throws Exception {

		int length = 2097152;

		FileOutputStream out = new FileOutputStream( f2 );
		byte[] buffer = new byte[length];
		while (true) {
			int ins = is.read( buffer );
			if ( ins == -1 ) {
				is.close( );
				out.flush( );
				out.close( );
				break;
			}
			out.write( buffer , 0 , ins );
		}
	}

使用方法如下:

String image =   "XXX.jpg";
File imageFile= new File(System.getProperty("java.io.tmpdir"), image); //System.getProperty("java.io.tmpdir")是获取操作系统缓存的临时目录
copyFileFromInputStream(XXXX.class.getResourceAsStream("images/" + image),imageFile);
// 系统会读取XXX.class路径中images文件夹下的xxx.jpg文件,将其转换为数据流

你可能感兴趣的:(java,html)