图片文件与二进制互转方法

本文介绍了一种将图片文件转换为二进制数据,再生成新的图片文件的方法,包括从图片文件中读取数据并将其转换为字节数组,然后将字节数组写入新的图片文件的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


/**
 * @title 读取图片文件将其转为二进制,再生成新的图片
 * 
 */
import java.awt.image.*;
import java.awt.*;
import java.io.*;
import java.sql.Blob;

import javax.imageio.*;

public class test {

 
 /**   
  *   转换byte数组为Image   
  *     
  *   @param   bytes   Image的bytes数据数组   
  *   @param   filename 为要生成新的文件名 
  *   @return   boolean   
  */
 public static boolean ByteToImage(byte[] b,String filename)
 {
  boolean bl=false;
  File binaryFile = new File("D:\\"+filename+".jpg"); 
  try {
   FileOutputStream fileOutStream = new FileOutputStream(binaryFile);
   for(int i=0;i<b.length;i++)
   {
    fileOutStream.write(b[i]);
   }
   fileOutStream.flush(); 
   bl=true;
  } catch (FileNotFoundException e) {
   // TODO 自动生成 catch 块
   e.printStackTrace();
  }//创建文件输出流。
  catch (IOException e) {
   // TODO 自动生成 catch 块
   e.printStackTrace();
  }
  return bl;
 }
 

 /*
  * 转换Image数据为byte数组   
  * */
 public static byte[] ImageToBytes(String path)
 {
File file = new File(path);//"C:\\Documents and Settings\\All Users\\Documents\\My Pictures\\示例图片\\Sunset.jpg"
FileInputStream fin = null;
try {
fin = new FileInputStream(file);
} catch (FileNotFoundException e1) {
  // TODO Auto-generated catch block
  e1.printStackTrace();
try {
ByteArrayOutputStream out= new ByteArrayOutputStream(); 
int i = fin.read();
while (i != -1) { 
  out.write(i); 
  i= fin.read(); 
return out.toByteArray();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return null;
 }
 
 

 
 public static void main(String args[])
 {

 
byte b[] = ImageToBytes("C:\\Documents and Settings\\All Users\\Documents\\My Pictures\\示例图片\\Sunset.jpg");
   
ByteToImage(b, "2");

 }
}

转载于:https://www.cnblogs.com/lorn/archive/2011/06/23/2087738.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值