Image与Base64String的互转换

     public Image Base64ToImage(string base64String)
        {
            // Convert Base64 String to byte[]
            byte[] imageBytes = Convert.FromBase64String(base64String);
            MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);

            // Convert byte[] to Image
            ms.Write(imageBytes, 0, imageBytes.Length);
            Image image = Image.FromStream(ms, true);
            return image;
        }


        public string CreateImgToBase64(string imagePath)
        {
            Bitmap bmp = (Bitmap)Image.FromFile(imagePath);
            MemoryStream stream = new MemoryStream();
            bmp.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);
            stream.Position = 0;
            byte[] data = new byte[stream.Length];
            stream.Read(data, 0, (int)stream.Length);
            stream.Close();

            string base64String = string.Empty;
            try
            {
                base64String = System.Convert.ToBase64String(data, 0, data.Length);
            }
            catch
            {
                throw;
            }

            StreamWriter outFile;

            try
            {
                outFile = new StreamWriter(string.Concat(imagePath, ".txt"), false, Encoding.ASCII);
                outFile.Write(base64String);
                outFile.Close();

                return base64String;
            }
            catch
            {
                throw;
            }

            bmp.Dispose();
        }

        public void CreateBase64StrToImage(string filePath)
        {
            StreamReader reader = new StreamReader(filePath);
            string str = reader.ReadToEnd();

            byte[] bitmapData = new byte[str.Length];
            bitmapData = Convert.FromBase64String(FixBase64ForImage(str));
            MemoryStream streamBitmap = new MemoryStream(bitmapData);

            Bitmap bitImage = new Bitmap((Bitmap)Image.FromStream(streamBitmap));
            bitImage.Save(filePath.Substring(0, filePath.Length - 4), System.Drawing.Imaging.ImageFormat.Jpeg);
            bitImage.Dispose();
        }

        static string FixBase64ForImage(string image)
        {
            StringBuilder sbText =
                new StringBuilder(image, image.Length);

            sbText.Replace("\r\n", string.Empty);
            sbText.Replace(" ", string.Empty);

            return sbText.ToString();
        }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值