首页 技术 正文
技术 2022年11月15日
0 收藏 506 点赞 3,932 浏览 1228 个字

前言

最近碰到了一些base64字符串转图片的开发任务,开始觉得没啥难度,但随着开发的进展还是发现有些东西需要记录下。

Base64 转二进制

这个在net有现有方法调用:

Convert.FromBase64String(str);

但在这一步发现调用时就报错了:Additional information: Base-64 字符数组或字符串的长度无效。

网上搜索下才发现要转换的Base64字符串应该为4的整数,如果不是的话要在字符串的末端加上‘=’将其补全为4的整数。

int mod4 = str.Length % 4;
if (mod4 > 0)
{
str += new string('=', 4 - mod4);
}

原生二进制数据转图片

现在通过Base64的转换我们有了图片的二进制数据,一开始就简单通过以下代码转换为图片:

Image image = Image.FromStream(new MemoryStream(byte));

但可惜的是,这一步也报错了,这里大概就猜到应该是我们的二进制数据没有包含头部信息,这样就导致转换无法继续。

所以最后的解决方案如下:

public Bitmap CopyDataToBitmap(int width,int height,byte[] data)
{
//Here create the Bitmap to the know height, width and format
Bitmap bmp = new Bitmap(width, height, PixelFormat.Format24bppRgb); //Create a BitmapData and Lock all pixels to be written
BitmapData bmpData = bmp.LockBits(
new Rectangle(0, 0, bmp.Width, bmp.Height),
ImageLockMode.WriteOnly, bmp.PixelFormat); //Copy the data from the byte array into BitmapData.Scan0
Marshal.Copy(data, 0, bmpData.Scan0, data.Length); //Unlock the pixels
bmp.UnlockBits(bmpData); //Return the bitmap
return bmp;
}

总结

以上就是base64字符串转图片碰到问题的汇总,这里记录下,并附带参考资料,有兴趣的同学可以参考下:

参考资料:

http://www.tek-tips.com/viewthread.cfm?qid=1264492

http://stackoverflow.com/questions/742236/how-to-create-a-bmp-file-from-byte-in-c-sharp

http://stackoverflow.com/questions/2925729/invalid-length-for-a-base-64-char-array

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,026
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,517
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,364
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,145
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,779
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,856