Welcome

首页 / 软件开发 / JAVA / Java中实现图片和字节数组之间的相互转化

Java中实现图片和字节数组之间的相互转化
方式一、
/**
*  通过图片路径将图片文件转化为字符数组
*  
* @param url 图片路径
* @return byte[]
*/
public static byte[] imageToBytes(String url){
	ByteArrayOutputStream byteOutput = new ByteArrayOutputStream();
    BufferedImage bufferedImage = null;
    try {
		bufferedImage = ImageIO.read(new File(url));
		ImageIO.write(bufferedImage,"jpg",byteOutput);
        return byteOutput.toByteArray();
	} catch (IOException e) {
		e.printStackTrace();
	}finally {
		try {
			if (byteOutput != null)
				byteOutput.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	return null;
}

/**
*  将图片字节数组转化为图片,存放到指定路径
*
* @param bytes 图片字节数组
* @param url 存放的路径
*/
public static void bytesToImage(byte[] bytes, String url){
    ByteArrayInputStream byteInput = new ByteArrayInputStream(bytes);
    BufferedImage bufferedImage = null;
    try {
        bufferedImage = ImageIO.read(byteInput);
        File file = new File(url);//可以是jpg,png,gif格式
        ImageIO.write(bufferedImage, "jpg", file);//不管输出什么格式图片,此处不需改动
    } catch (IOException e) {
        e.printStackTrace();
    }finally{
        try {
        	if (byteInput != null)
            	byteInput.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

方式二、利用字节流来实现
/**
*  通过图片路径将图片文件转化为字符数组
*  
* @param url 图片路径
* @return byte[]
*/
public static byte[] ImageToBytes(String url){
    FileImageInputStream input = null;
    ByteArrayOutputStream output = null;
    try {
        input = new FileImageInputStream(new File(url));
        output = new ByteArrayOutputStream();
        byte[] buf = new byte[1024];
        int numBytesRead = 0;
        while ((numBytesRead = input.read(buf)) != -1) {
            output.write(buf, 0, numBytesRead);
        }
        return output.toByteArray();
    } catch (IOException e) {
        e.printStackTrace();
    }finally {
        try {
            if (input != null)
                input.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            if (output != null)
                output.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;
}

/**
*  将图片字节数组转化为图片,存放到指定路径
*
* @param bytes 图片字节数组
* @param url 存放的路径
*/
public static void BytesToImage(byte[] bytes, String url){
    FileImageOutputStream imageOutput = null;//打开输入流
    try {
        imageOutput = new FileImageOutputStream(new File(url));
        imageOutput.write(bytes, 0, bytes.length);//将byte写入硬盘
    } catch (IOException e) {
        e.printStackTrace();
    }finally {
        try {
            if (imageOutput != null)
                imageOutput.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}