问题描述
在做一个小东西,其中有一个功能是把C盘根目录下的一个BMP文件转换成JPG文件,同时将这个图片文件编码成base64StringImagefilename=@“C:TEMP.BMP”;Bitmapbmp=newBitmap(Imagefilename);this.pictureBox1.Image=bmp;MemoryStreamms=newMemoryStream();bmp.Save(ms,System.Drawing.Imaging.ImageFormat.Jpeg);byte[]arr=newbyte[ms.Length];ms.Position=0;ms.Read(arr,0,(int)ms.Length);ms.Close();Stringstrbaser64=Convert.ToBase64String(arr);base64text.Text=strbaser64;
要转成JPG再编码base64的原因是如果直接转码bmp报错但是这样转码后,得到的base64结果是错的,无法还原为图片百度过很久,没搞明白所以然……
解决方案
本帖最后由 ynwr_xj 于 2016-02-23 16:26:47 编辑
解决方案二:
{returnSystem.Convert.ToBase64String(ImageToBytes(s,System.Drawing.Imaging.ImageFormat.Png));}staticbyte[]ImageToBytes(BitmapImage,System.Drawing.Imaging.ImageFormatimageFormat){if(Image==null){returnnull;}byte[]data=null;using(MemoryStreamms=newMemoryStream()){using(BitmapBitmap=Image){Bitmap.Save(ms,imageFormat);ms.Position=0;data=newbyte[ms.Length];ms.Read(data,0,Convert.ToInt32(ms.Length));ms.Flush();}}returndata;}privateBitmapbase64(strings){returnnewBitmap(byteArrayToImage(System.Convert.FromBase64String(s)));}System.Drawing.ImagebyteArrayToImage(byte[]byteArrayIn){if(byteArrayIn==null)returnnull;using(System.IO.MemoryStreamms=newSystem.IO.MemoryStream(byteArrayIn)){System.Drawing.ImagereturnImage=System.Drawing.Image.FromStream(ms);ms.Flush();returnreturnImage;}}
解决方案三:
staticstringbase64(Bitmaps){returnSystem.Convert.ToBase64String(ImageToBytes(s,System.Drawing.Imaging.ImageFormat.Png));}staticbyte[]ImageToBytes(BitmapImage,System.Drawing.Imaging.ImageFormatimageFormat){if(Image==null){returnnull;}byte[]data=null;using(MemoryStreamms=newMemoryStream()){using(BitmapBitmap=Image){Bitmap.Save(ms,imageFormat);ms.Position=0;data=newbyte[ms.Length];ms.Read(data,0,Convert.ToInt32(ms.Length));ms.Flush();}}returndata;}privateBitmapbase64(strings){returnnewBitmap(byteArrayToImage(System.Convert.FromBase64String(s)));}System.Drawing.ImagebyteArrayToImage(byte[]byteArrayIn){if(byteArrayIn==null)returnnull;using(System.IO.MemoryStreamms=newSystem.IO.MemoryStream(byteArrayIn)){System.Drawing.ImagereturnImage=System.Drawing.Image.FromStream(ms);ms.Flush();returnreturnImage;}}
没贴完整。补齐一下。-_-。sorry!