java图片转byte转string

时间:2021-12-15 11:49:30

第一种:原始乱码:

public static void main(String[] args) throws IOException {
            File imgFile = new File("d:\\1.jpg");   
            FileInputStream fis = new FileInputStream( imgFile );   
            byte[] bytes = new byte[fis.available()];   
            fis.read(bytes);   
            fis.close();   
            String imgStr = new String(bytes);   
            System.out.println( imgStr);      
    }

第二种:完整字节:

public String byteToString(byte[] buf){
        String str1="";
        StringBuilder sb=new StringBuilder(str1);
        for (byte element: buf )
        {
        sb.append(element);
        }
        str1=sb.toString();
        return str1;
    }
    public static void main(String[] args) throws IOException {
            File imgFile = new File("d:\\1.jpg");   
            FileInputStream fis = new FileInputStream( imgFile );   
            byte[] bytes = new byte[fis.available()];   
            fis.read(bytes);   
            fis.close();   
            String imgStr = new Byte().byteToString(bytes);   
            System.out.println( imgStr);      
    }