好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

java读取图片并转化为二进制字符串的实现方法

本例子的目的在于测试往oracle数据库中插入blob字段

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

public static string getimgstr(string imgfile){

   //将图片文件转化为字节数组字符串,并对其进行base64编码处理

  

   inputstream in = null ;

   byte [] data = null ;

   //读取图片字节数组

   try

   {

    in = new fileinputstream(imgfile); 

    data = new byte [in.available()];

    in.read(data);

    in.close();

   }

   catch (ioexception e)

   {

    e.printstacktrace();

   }

   return new string(base64.encodebase64(data));

  }

--

利用以上的思路写的一个测试

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

public class readimagetest {

  public static void main(string[] args) throws ioexception {

    fileinputstream fis = new fileinputstream( new file( "c:\\users\\luzhifei\\pictures\\hc_logo.png" ));  

    string picstr= "" ;

    byte [] read = null ;

    int len = 0 ;

    read= new byte [fis.available()];

    fis.read(read);

    string basestr= base64.getencoder().encodetostring(read);

    //system.out.println( basestr);

    byte [] op= base64.getdecoder().decode(basestr);

    // system.out.println(new string(op));

    fileoutputstream fos = new fileoutputstream( new file( "d:\\temp\\1.jpg" ));

    fos.write(op, 0 ,op.length );

    fos.flush();

    fos.close();

  }

}

但是available()有一定的限制。

为了稳妥,严重建议采取以下方式:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

public static void imagetobase64str() throws ioexception{

    fileinputstream fis = new fileinputstream( new file( "c:\\users\\luzhifei\\pictures\\hc_logo.png" ));

    byte [] read = new byte [ 1024 ];

    int len = 0 ;

    list< byte []> blist= new arraylist< byte []>();

    int ttllen= 0 ;

    while ((len = fis.read(read))!= - 1 ){

     byte [] dst= new byte [len];

     system.arraycopy(read, 0 , dst, 0 , len);

     ttllen+=len;

     blist.add(dst);

    }

    fis.close();

    byte [] dstbyte= new byte [ttllen];

    int pos= 0 ;

    for ( int i= 0 ;i<blist.size();i++){

     if (i== 0 ){

      pos= 0 ;

     }

     else {

     pos+=blist.get(i- 1 ).length;

     }

     system.arraycopy(blist.get(i), 0 , dstbyte, pos, blist.get(i).length);

    }

    string basestr= base64.getencoder().encodetostring(dstbyte);

    byte [] op= base64.getdecoder().decode(basestr);

    fileoutputstream fos = new fileoutputstream( new file( "d:\\temp\\2.jpg" ));

    fos.write(op, 0 ,op.length );

    fos.flush();

    fos.close();

  }

总结

以上所述是小编给大家介绍的java读取图片并转化为二进制字符串,希望对大家有所帮助,如果大家有任何疑问欢迎给我留言,小编会及时回复大家的!

原文链接:https://HdhCmsTestcnblogs测试数据/lzfhope/archive/2018/09/16/java_read_binary_file.html

查看更多关于java读取图片并转化为二进制字符串的实现方法的详细内容...

  阅读:43次