Reputation: 4571
I am trying to use the ImageConverter
class in my ASP.NET Core project to convert an Image
to a byte[]
, but I can't seem to find the class.
I have installed the System.Drawing.Common package, but still can't find it.
I am using .NET Core 3.1.
Upvotes: 5
Views: 8904
Reputation: 690
Instead of ImageConverter, you can trying to look at this for speed up:
Save bitmap to stream:
bitmap.save(stream);
Or open image file:
FileStream stream = new FileStream(imageFilePath, FileMode.Open, FileAccess.Read);
Then simply use Stream2Bytes:
byte[] OO7b = Stream2Bytes(stream);
And this is the Stream2Bytes method:
public byte[] Stream2Bytes(Stream stream, int chunkSize = 1024)
{
if (stream == null)
{
throw new System.ArgumentException("Parameter cannot be null", "stream");
}
if (chunkSize < 1)
{
throw new System.ArgumentException("Parameter must be greater than zero", "chunkSize");
}
if (chunkSize > 1024 * 64)
{
throw new System.ArgumentException(String.Format("Parameter must be less or equal {0}", 1024 * 64), "chunkSize");
}
List<byte> buffers = new List<byte>();
using (BinaryReader br = new BinaryReader(stream))
{
byte[] chunk = br.ReadBytes(chunkSize);
while (chunk.Length > 0)
{
buffers.AddRange(chunk);
chunk = br.ReadBytes(chunkSize);
}
}
return buffers.ToArray();
}
Upvotes: 0
Reputation: 3617
If on .NET Core 3.1, ImageConverter
requires the System.Windows.Extensions
package:
https://learn.microsoft.com/en-us/dotnet/api/system.drawing.imageconverter?view=netcore-3.1
In .NET 5 it is included in System.Drawing.Common
:
https://learn.microsoft.com/en-us/dotnet/api/system.drawing.imageconverter?view=net-5.0
Upvotes: 4
Reputation: 1721
You can convert image to byte easily.
protected virtual byte[] LoadPictureFromFile(string filePath)
{
if (!File.Exists(filePath))
return new byte[0];
return File.ReadAllBytes(filePath);
}
Extra help..
public byte[] ResizeImage(byte[] pictureBinary,int newWidth, int newHeight)
{
byte[] pictureBinaryResized;
using (var stream = new MemoryStream(pictureBinary))
{
Bitmap b = null;
try
{
//try-catch to ensure that picture binary is really OK. Otherwise, we can get "Parameter is not valid" exception if binary is corrupted for some reasons
b = new Bitmap(stream);
}
catch (ArgumentException exc)
{
// log error
}
if (b == null)
{
//bitmap could not be loaded for some reasons
return new byte[0];
}
using (var destStream = new MemoryStream())
{
ImageBuilder.Current.Build(b, destStream, new ResizeSettings
{
Width = newWidth,
Height = newHeight,
Scale = ScaleMode.Both,
Quality = _mediaSettings.DefaultImageQuality
});
pictureBinaryResized = destStream.ToArray();
b.Dispose();
}
}
return pictureBinaryResized;
}
Upvotes: 0