本例子的目的在于测试往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
相关文章
猜你喜欢
- ASP.NET本地开发时常见的配置错误及解决方法? 2025-06-10
- ASP.NET自助建站系统的数据库备份与恢复操作指南 2025-06-10
- 个人网站服务器域名解析设置指南:从购买到绑定全流程 2025-06-10
- 个人网站搭建:如何挑选具有弹性扩展能力的服务器? 2025-06-10
- 个人服务器网站搭建:如何选择适合自己的建站程序或框架? 2025-06-10
TA的动态
- 2025-07-10 怎样使用阿里云的安全工具进行服务器漏洞扫描和修复?
- 2025-07-10 怎样使用命令行工具优化Linux云服务器的Ping性能?
- 2025-07-10 怎样使用Xshell连接华为云服务器,实现高效远程管理?
- 2025-07-10 怎样利用云服务器D盘搭建稳定、高效的网站托管环境?
- 2025-07-10 怎样使用阿里云的安全组功能来增强服务器防火墙的安全性?
快网idc优惠网
QQ交流群
您的支持,是我们最大的动力!
热门文章
-
2025-05-29 43
-
2025-05-25 51
-
2025-05-29 73
-
2025-05-27 83
-
2025-05-29 48
热门评论

