当前位置:网站首页>Copy the picture

Copy the picture

2020-11-08 21:03:50 8Years

public class TestBytesInputStream {

    public static void main(String[] args) {
        // Copy a.jpg picture 
        byte[] datas=fileToBytesArray("D:\\a.jpg");
        byteArrayToFile(datas,"D:\\b.jpg");



    }

//1. The image is read into the byte array 
//  1. Picture to program ——FileInputStream
//  2. Program to byte array ——byteArrayOutputStream


    public static byte[] fileToBytesArray(String path) {
        // Create source and destination 
        File src = new File(path);
        byte[] dest = null;
        // Select flow 
        InputStream is = null;
        ByteArrayOutputStream baos = null;


        try {
             // You can also use   is = new BufferedInputStream(FileInputStream(src));
            is = new FileInputStream(src);
            // You can also use baos = new BufferedOutputStream(teArrayOutputStream());
            baos = new ByteArrayOutputStream();
            //3. Segment read 
            byte[] flush = new byte[1024 * 10];// Buffer container 
            int len = -1;
            while ((len = is.read(flush)) != -1) {
                baos.write(flush, 0, len);// Write to a byte array 
            }
            baos.flush();
            return baos.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != is) {
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static void byteArrayToFile(byte[]src,String path){
        File dest=new File(path);
        InputStream is=null;
        OutputStream os=null;
        try {
            is = new ByteArrayInputStream(src);
            os = new FileOutputStream(dest);
            byte[] flush = new byte[5];
            int len = -1;
            while ((len = is.read(flush)) != -1) {
                os.write(flush, 0, len);
            }

        }catch (IOException e) {
            e.printStackTrace();
        } finally {
            try{
                if(os!=null){
                    os.close();
                }
            }catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

It's worth reminding , When is.read() When no parameters are passed in , The copied image will not open , Because it can only read byte by byte , So it's better to pass in the array

 

Two places to improve performance (1. The use of buffer containers ( It's like a pickup truck )    2. You can also use byte buffer streams ( It's like a big truck ))

版权声明
本文为[8Years]所创,转载请带上原文链接,感谢