java接收图片数据的字节数组并保存

来源:互联网 发布:淘宝上1元包邮赚钱吗 编辑:程序博客网 时间:2024/05/10 08:22
import java.io.*;
import java.net.*;
/**
 模拟一个jpeg位图到byte[]
 */
class Image2Buff
{
    static byte[] image2Bytes(String imgSrc) throws Exception
    {
        FileInputStream fin = new FileInputStream(new File(imgSrc));
        //可能溢出,简单起见就不考虑太多,如果太大就要另外想办法,比如一次传入固定长度byte[]
        byte[] bytes  = new byte[fin.available()];
        //将文件内容写入字节数组,提供测试的case
        fin.read(bytes);
        fin.close();
        return bytes;
    }
 
    //从网上读取图片地址,存入本地
    static byte[] image2BytesFromURL(String address) throws Exception
    {
        URL url = new URL(address);
        InputStream is = url.openStream();
        byte[] bytes  = new byte[is.available()];
        //将文件内容写入字节数组,提供测试的case
        is.read(bytes);
        return bytes;
    }
 
}
 
class Buff2Image
{
    /**
     @param b 传入的byte
     @param tagSrc 目标文件名
         
     */
    static void buff2Image(byte[] b,String tagSrc) throws Exception
    {
        FileOutputStream fout = new FileOutputStream(tagSrc);
        //将字节写入文件
        fout.write(b);
        fout.close();
    }
}
 
  
public class ImageBufTest
{
    public static void main(String[] args) throws Exception
    {
        //先模拟一个图形byte[]
        byte[] b = Image2Buff.image2Bytes("c:/1.jpg");
        //存为文件
        Buff2Image.buff2Image(b,"c:/test.jpg");
        //通过url 读取图片得到bytes,复制你的头像到本地
        byte[] b2 = Image2Buff.image2BytesFromURL("http://avatar.profile.csdn.net/D/C/3/1_hjx_code.jpg");
        Buff2Image.buff2Image(b2,"c:/test2.jpg");
        System.out.println("Hello World!");
    }
}
原创粉丝点击