[英]Parameter is not valid - From byte to bitmap
我有一個字節數組,數組的大小是3104982 ~ 2.9 MB
。 我想創建此圖像的位圖,但遇到parameter is not valid - ArgumentException
我嘗試了幾種選擇:
public static Bitmap ByteArrayToBitmap(byte[] blob)
{
using (var mStream = new MemoryStream())
{
mStream.Write(blob, 0, blob.Length);
mStream.Position = 0;
var bm = new Bitmap(mStream);
return bm;
}
}
和
public static Bitmap ByteArrayToBitmap(byte[] blob)
{
TypeConverter tc = TypeDescriptor.GetConverter(typeof(Bitmap));
Bitmap bitmap1 = (Bitmap) tc.ConvertFrom(blob);
return bitmap1;
}
但是仍然會發生異常。 有任何想法嗎?
我認為您不知道位圖的Width
和Height
就不會這樣做。
長度為120000像素可能來自300x400位圖,400x300或200x600或600x100或12000x10。
系統將如何從原始 ByteArray的Length中推斷出它?
同樣,必須知道PixelFormat
(顏色深度,數量和每像素字節的含義)才能創建位圖。
如何創建ByteArray?
如果byte[]
是格式化的數據,則:
return Image.FromStream(mStream);
如果您確定數據為Bitmap
則可能要將其轉換為Bitmap
。
return (Bitmap)Image.FromStream(mStream);
我已經使用控制台程序對其進行了測試,並且對我來說效果很好。
class Program
{
static void Main(string[] args)
{
const string fileName = @"H:\Stackoverflow\C#\20140601 - Question 1\Image\DSC_0004b.jpg";
//const string fileName = @"H:\Stackoverflow\C#\20140601 - Question 1\Image\Test.txt";
byte[] blob;
try
{
using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
{
blob = new byte[fs.Length];
fs.Read(blob, 0, (int)fs.Length);
}
Bitmap bitmap = ByteArrayToBitmap(blob);
Console.WriteLine("Height = {0}, Width = {1}", bitmap.Height, bitmap.Width);
}
catch (ArgumentException e)
{
Console.WriteLine(e.Message);
}
}
protected static Bitmap ByteArrayToBitmap(byte[] blob)
{
using (var mStream = new MemoryStream())
{
mStream.Write(blob, 0, blob.Length);
mStream.Position = 0;
var bm = new Bitmap(mStream);
return bm;
}
}
}
測試結果顯示為:
Height = 3076, Width = 2104
Press any key to continue . . .
如果我使用文本文件而不是圖像文件,則它會引發您所描述的ArgumentException。 它顯示:
Parameter is not valid.
Press any key to continue . . .
當我對它進行編碼時,引發異常的確切行是:
var bm = new Bitmap(mStream);
當您檢查ArgumentException對象時,不幸的是其中沒有更多有用的信息。 (例如,參數名稱會有所幫助。)
可能是您在blob參數中輸入了無效數據嗎?
您可能需要改進異常處理,以便其提供更多信息。 例如:
protected static Bitmap ByteArrayToBitmap(byte[] blob)
{
using (var mStream = new MemoryStream())
{
mStream.Write(blob, 0, blob.Length);
mStream.Position = 0;
try
{
var bm = new Bitmap(mStream);
return bm;
}
catch (Exception ex)
{
throw new ArgumentException("Not a valid bitmap.", "blob", ex);
}
}
}
嘗試這個
public Bitmap changeByteToImage( Byte[] imagedata )
{
System.IO.MemoryStream ms=new System.IO.MemoryStream(imagedata);
Bitmap picdata=new Bitmap(Image.FromStream(ms));
return picdata;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.