2013-02-20 23 views
0

我目前正在嘗試將圖像大小調整爲縮略圖,以在完成上傳時顯示爲預覽。我正在使用fineuploader插件來上傳圖片的一部分。我一直不斷收到「參數無效」。我見過很多與此相關的帖子,並嘗試了大部分解決方案,但沒有成功。這裏是代碼片段:將圖像調整爲字節數組的大小

public static byte[] CreateThumbnail(byte[] PassedImage, int LargestSide) 
    { 
     byte[] ReturnedThumbnail = null; 

     using (MemoryStream StartMemoryStream = new MemoryStream(), 
          NewMemoryStream = new MemoryStream()) 
     { 
      StartMemoryStream.Write(PassedImage, 0, PassedImage.Length); //error being fire in this line 

      System.Drawing.Bitmap startBitmap = new Bitmap(StartMemoryStream); 

      int newHeight; 
      int newWidth; 
      double HW_ratio; 
      if (startBitmap.Height > startBitmap.Width) 
      { 
       newHeight = LargestSide; 
       HW_ratio = (double)((double)LargestSide/(double)startBitmap.Height); 
       newWidth = (int)(HW_ratio * (double)startBitmap.Width); 
      } 
      else 
      { 
       newWidth = LargestSide; 
       HW_ratio = (double)((double)LargestSide/(double)startBitmap.Width); 
       newHeight = (int)(HW_ratio * (double)startBitmap.Height); 
      } 

      System.Drawing.Bitmap newBitmap = new Bitmap(newWidth, newHeight); 

      newBitmap = ResizeImage(startBitmap, newWidth, newHeight); 

      newBitmap.Save(NewMemoryStream, System.Drawing.Imaging.ImageFormat.Jpeg); 

      ReturnedThumbnail = NewMemoryStream.ToArray(); 
     } 

     return ReturnedThumbnail; 
    } 

我出來的想法,任何幫助表示讚賞。

回答

0

你的錯誤是在new Bitmap(startMemoryStream)行,而不是上面的行。

documentation指出時,可能發生此異常:

流不包含圖像數據或爲空。

- 或 -

流包含具有單一尺寸大於65,535個像素大的PNG圖像文件。

你應該檢查你有沒有一個有效的PNG文件。例如,將其寫入文件並嘗試在圖像查看器中打開它。

+0

我會嘗試寫入一個文件,不知道它必須是一個PNG文件,謝謝指出。 – rdk1992 2013-02-20 16:44:18

+0

圖像有效,因爲原始圖像已成功存儲在SharePoint列表中。當我成功打印出它的長度時,字節數組不是空的。有任何想法嗎? – rdk1992 2013-02-20 17:01:00

+0

我通過從文件加載我自己的PNG到字節並提供它,測試了部分方法,並且它工作正常。此方法中的代碼在構造函數之前是正確的。因此,從SharePoint列表中讀取圖像的代碼可能存在問題?再次,使用'BinaryWriter'和'File.Create'將您的字節寫入文件並查看它是否正確。 – Virtlink 2013-02-20 17:06:15

0

該代碼是危險的 - System.Drawing類必須將放置在using(){}子句中。

下面是使用ImageResizer NuGet包並安全調整圖像大小的備用解決方案。

var ms = new MemoryStream(); 
ImageResizer.Current.Build(PassedImage, ms, new ResizeSettings(){MaxWidth=LargestSide, MaxHeight=LargestSide}); 
return ImageResizer.ExtensionMethods.StreamExtensions.CopyToBytes(ms);