You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
49 lines
1.4 KiB
49 lines
1.4 KiB
using System.Drawing;
|
|
using System.Drawing.Imaging;
|
|
using System.IO;
|
|
|
|
namespace Infrastructure.Extensions
|
|
{
|
|
public static class BitmapExtensions
|
|
{
|
|
public static byte[] ToBytes(this Bitmap bitmap)
|
|
{
|
|
if (bitmap is null)
|
|
{
|
|
throw new System.ArgumentNullException(nameof(bitmap));
|
|
}
|
|
|
|
using var stream = new MemoryStream();
|
|
bitmap.Save(stream, ImageFormat.Jpeg);
|
|
return stream.ToArray();
|
|
}
|
|
|
|
public static byte[] ToJpeg(this Bitmap bitmap, long quality = 50)
|
|
{
|
|
if (bitmap is null)
|
|
{
|
|
throw new System.ArgumentNullException(nameof(bitmap));
|
|
}
|
|
|
|
var jpgEncoder = GetEncoder(ImageFormat.Jpeg);
|
|
using var parameters = new EncoderParameters(1);
|
|
parameters.Param[0] = new EncoderParameter(Encoder.Quality, quality);
|
|
using var stream = new MemoryStream();
|
|
bitmap.Save(stream, jpgEncoder, parameters);
|
|
return stream.ToArray();
|
|
}
|
|
|
|
private static ImageCodecInfo GetEncoder(ImageFormat format)
|
|
{
|
|
ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();
|
|
foreach (ImageCodecInfo codec in codecs)
|
|
{
|
|
if (codec.FormatID == format.Guid)
|
|
{
|
|
return codec;
|
|
}
|
|
}
|
|
return null;
|
|
}
|
|
}
|
|
} |