如何将base64位的字节数组转换成图片并显示
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何将base64位的字节数组转换成图片并显示相关的知识,希望对你有一定的参考价值。
不用保存成文件。写一个servlet(假设名字是servletImg),页面的参数就是 id,然后将从DB得到的图像的byte[],通过流输出给页面。
页面还是 <img src="servletImg?id=1234" />
这样的逻辑,才行。 参考技术A 在C#中
图片到byte[]再到base64string的转换:
Bitmap bmp = new Bitmap(filepath);
MemoryStream ms = new MemoryStream();
bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
byte[] arr = new byte[ms.Length];
ms.Position = 0;
ms.Read(arr, 0, (int)ms.Length);
ms.Close();
string pic = Convert.ToBase64String(arr);
base64string到byte[]再到图片的转换:
byte[] imageBytes = Convert.FromBase64String(pic);
//读入MemoryStream对象
MemoryStream memoryStream = new MemoryStream(imageBytes, 0, imageBytes.Length);
memoryStream.Write(imageBytes, 0, imageBytes.Length);
//转成图片
Image image = Image.FromStream(memoryStream);
如何将图像的字节数组转换为表示 jpg 的 base64 编码字符串
【中文标题】如何将图像的字节数组转换为表示 jpg 的 base64 编码字符串【英文标题】:How to convert byte array of an image to a base64 encoded string representing a jpg 【发布时间】:2015-08-21 02:16:36 【问题描述】:我正在编写一个拍摄照片并上传照片的 Android 应用。
API 需要一个表示要上传的 jpg 的 base 64 编码字符串。
Camera API 给了我一个byte []
。
如何将此字节数组转换为 base64 编码字符串,以确保保持 jpg 格式?
目前,我正在尝试String encoded = Base64.encodeToString(byteArray, Base64.NO_WRAP);
但这不知何故是无效的,在日志中给了我一堆AAAAAAAAA
s,而不是真正的base64编码字符串。
感谢您的帮助
编辑:
其实,当我退出上面encoded
的内容时,我得到了
/9j/4UVIRXhpZgAATU0AKgAAAAgACQEPAAIAAAAPAAAAegEQAAIAAAAJAAAAigESAAMAAAABAAEAAAEaAAUAAAABAAAAlAEbAAUAAAABAAAAnAEoAAMAAAABAAIAAAITAAMAAAABAAEAAIdpAAQAAAABAAAApI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JOPxpAR3Dfvs+wpsjnyz6Uy5bEin1FGSYmzQMr78w5x6VXf/AI+STUhfEZFRStiYe4FAx+nHZq0a+rGun6Vy1thdXhP/AE0H611TCtI7GNTcYTTCaeaYaozGcUxgDTyKjNAGbqV09rGCgyScc9qwHuZ7iTBVnJ9K29YH7pPrVSzUeQMAZzQBBFZE4Mp/4CKsqixjCqBVuO1klG77q+pqykEUQ6bm9TTGUo7WSXBAwPU1cjtIouWO9vfpTnnCjriqz3JPCimBbaUKOOBVaS5HQc1WZmbqaTbQArys/Un6UzaakAxRQAwJSYp9IaYEZGO9NxUhppoAux8oPpVy1XKzD/YqpDzGv0q7ZffdfVDTJMmdcSVow8wofaqd0uHNXrbm3T6UIC9pXy6lAf8AaFddtrj7L5LuJvRwf1rtStJiKsyZiNUGStaRco30rPdaQFMr7Um2pytJsqkIiC04LUgSnBaoCMLShalCU8JQBEEpwSpQtOCe1AEQWnbamCU4J7UAQhM04JUwT2p4SmBBspRH7VY2e1KEpAYDR1E0dXCPaoXHtWpzoytVQf2fJ7AH9a58qAK6XU1zp0/+4a51h8ufSuav0OvD7MUL+5XjuRSxkB04pV5hHsaBgMp5rGHxI3lsbqqrIMgHimvbRMOUFTIMxr9Kdtr0rI47sxr23jiKlOOelERZo8lcH61b1GP5EPvV
但是当它实际发布到服务器时(使用 Square 的 Retrofit 库),我会收到数十万个 AAAAA
s,这会破坏服务器。
尽管如此,但记录的编码字符串似乎不够长,无法封装与 LG G3 中的照片相关的所有数据。
【问题讨论】:
Base64.encodeBase64(byteArray).toString()
?
您尝试以哪种格式保存在服务器上????????
【参考方案1】:
使用
byte [] data = Base64.decode(base64str);
您需要在项目中引用 commons codec 才能使该代码正常工作。
【讨论】:
以上是关于如何将base64位的字节数组转换成图片并显示的主要内容,如果未能解决你的问题,请参考以下文章
如何将图像的字节数组转换为表示 jpg 的 base64 编码字符串