读取图像为base64字符串;内存不足异常

时间:2016-04-25 08:32:49

标签: c# asp.net

我正在尝试将目录中的图像转换为base64字符串。当我在本地计算机上测试它时它可以工作,但在服务器上它会给出内存不足的异常: 这是我的方法:

 private ImageDataViewModel ReadImagesFromDisk(Guid id)
    {
        List<string> imageList = new List<string>();
        ImageDataViewModel imageDataViewModel = new ImageDataViewModel();
        string path = HttpContext.Current.Server.MapPath("~/BusinessImages/" + id.ToString());
        try
        {
            if (Directory.Exists(path))
            {
                var images = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories)
                    .ToList();

                string fileName = id.ToString();

                foreach (var item in images)
                {

                    using (Image image = Image.FromFile(item))
                    {
                        using (MemoryStream m = new MemoryStream())
                        {
                            image.Save(m, image.RawFormat);
                            byte[] imageBytes = m.ToArray();
                            // Convert byte[] to Base64 String
                            string base64String = Convert.ToBase64String(imageBytes);                                                        
                            imageList.Add(base64String);                                                     
                        }
                    }
                }
                imageDataViewModel.Id = id;
                imageDataViewModel.ImageData = imageList;

                return imageDataViewModel;
            }
            else
            {
                return null;
            }
        }
        catch (Exception ex)
        {

            throw ex;
        }            
    }

我不知道这是怎么发生的。有没有办法解决这个问题?

1 个答案:

答案 0 :(得分:0)

byte[] fileBytes = System.IO.File.ReadAllBytes(yourfilepath + fname);
string fileName = yourfilename.Split(new string[] { "/" }, StringSplitOptions.None)[1];
return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);

try this, This will return whole file.