2016-04-25 31 views
0

我試圖將目錄中的圖像轉換爲base64字符串。當我在本地計算機上測試它的工作原理,但在服務器上就給出了內存的異常: 這裏是我的方法:閱讀Image as 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; 
     }    
    } 

我不知道這是如何發生。有什麼辦法可以解決這個問題嗎?

+0

OOM可能是由於很多原因造成的。可能是服務器上有太多沉重的圖像可能是在此操作過程中發生的任何其他並行任務正在消耗內存。你是否得到堆棧跟蹤線路崩潰?> – Nitin

+0

你把所有你的圖像放在base64的imageList內存中,也許你是爲每個請求做了這樣的事情,所以在一個真正的活動的服務器中,你探索了服務器的內存容量。嘗試一個單身,以確保你只做過一次。 –

+0

爲什麼你想要在主內存中存儲圖像列表?而Base 64字符串需要的空間是原始字節數組的2.7倍... – Codo

回答

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); 

試試這個, 這將返回整個文件。