/// <summary>
        /// Base64转换图片
        /// </summary>
        /// <param name="strbase64"></param>
        /// <returns></returns>
        public static string Base64StringToImage(string strbase64)
        {
            strbase64 = strbase64.Replace("data:image/png;base64,", string.Empty);
            string newDirectoryPath = "";
            string DirectoryPath = null;
            try
            {
                DirectoryPath = "XJReportImaging/";
                string path = SysConfig.GetFileServerUpload(DirectoryPath);
                if (!Directory.Exists(path))
                    Directory.CreateDirectory(path);
                DirectoryPath += "共性问题图片" + string.Format("{0:yyyyMMddHHmmssffff}", DateTime.Now) + ".png";
                newDirectoryPath = SysConfig.GetFileServerUpload(DirectoryPath);

                byte[] arr = Convert.FromBase64String(strbase64);
                MemoryStream ms = new MemoryStream(arr);
                Bitmap original = (Bitmap)Image.FromStream(ms);

                //获取图片宽度
                int sourceWidth = original.Width;
                //获取图片高度
                int sourceHeight = original.Height;

                float nPercent = 0;
                float nPercentW = 0;
                float nPercentH = 0;
                //计算宽度的缩放比例
                nPercentW = ((float)1000 / (float)sourceWidth);
                //计算高度的缩放比例
                nPercentH = ((float)4000 / (float)sourceHeight);

                if (nPercentH < nPercentW)
                    nPercent = nPercentH;
                else
                    nPercent = nPercentW;
                //期望的宽度
                int destWidth = (int)(sourceWidth * nPercent);
                //期望的高度
                int destHeight = (int)(sourceHeight * nPercent);

                Bitmap bmp = new Bitmap(original, new Size(destWidth, destHeight));
                //bmp.SetResolution(original.HorizontalResolution, original.VerticalResolution);
                using (var g = Graphics.FromImage(bmp))
                {
                    g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    g.DrawImage(original, 0, 0, destWidth, destHeight);
                    //g.Clear(Color.White);
                    //g.DrawImageUnscaled(original, 0, 0);
                }
                
                bmp.Save(newDirectoryPath, System.Drawing.Imaging.ImageFormat.Png);
                ms.Close();

                return DirectoryPath;



                //return bmp;
            }
            catch (Exception ex)
            {
                return null;
            }

        }

 

posted on 2022-04-24 18:09  水。  阅读(744)  评论(0编辑  收藏  举报