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

2025-05-29 0 57

本例子的目的在于测试往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://www.cnblogs.com/lzfhope/archive/2018/09/16/java_read_binary_file.html

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 java读取图片并转化为二进制字符串的实现方法 https://www.kuaiidc.com/110920.html

相关文章

发表评论
暂无评论