DocSpace-client/web/ASC.Web.Core/CommonPhotoManager.cs

84 lines
2.7 KiB
C#
Raw Normal View History

2019-06-07 08:59:07 +00:00
namespace ASC.Web.Core
{
2022-01-21 10:47:56 +00:00
public static class CommonPhotoManager
2019-06-07 08:59:07 +00:00
{
public static Image DoThumbnail(Image image, Size size, bool crop, bool transparent, bool rectangle)
{
var width = size.Width;
var height = size.Height;
var realWidth = image.Width;
var realHeight = image.Height;
Image thumbnail;
2019-06-07 08:59:07 +00:00
var maxSide = realWidth > realHeight ? realWidth : realHeight;
var minSide = realWidth < realHeight ? realWidth : realHeight;
2022-01-12 12:34:58 +00:00
var alignWidth = crop ? (minSide == realWidth) : (maxSide == realWidth);
2019-06-07 08:59:07 +00:00
2022-01-21 13:46:30 +00:00
var scaleFactor = alignWidth ? (realWidth / (1.0 * width)) : (realHeight / (1.0 * height));
2019-06-07 08:59:07 +00:00
if (scaleFactor < 1) scaleFactor = 1;
int locationX, locationY;
int finalWidth, finalHeigth;
finalWidth = (int)(realWidth / scaleFactor);
finalHeigth = (int)(realHeight / scaleFactor);
if (rectangle)
{
thumbnail = new Image<Rgba32>(width, height);
2019-06-07 08:59:07 +00:00
locationY = (int)((height / 2.0) - (finalHeigth / 2.0));
locationX = (int)((width / 2.0) - (finalWidth / 2.0));
2019-08-15 15:08:40 +00:00
if (!transparent)
2019-06-07 08:59:07 +00:00
{
thumbnail.Mutate(x=> x.Clear(Color.White));
2019-06-07 08:59:07 +00:00
}
var point = new Point(locationX, locationY);
image.Mutate(y => y.Resize(finalWidth, finalHeigth));
thumbnail.Mutate(x => x.DrawImage(image, point, 1));
2019-06-07 08:59:07 +00:00
}
else
{
thumbnail = new Image<Rgba32>(finalWidth, finalHeigth);
2019-06-07 08:59:07 +00:00
2019-08-15 15:08:40 +00:00
if (!transparent)
2019-06-07 08:59:07 +00:00
{
thumbnail.Mutate(x => x.Clear(Color.White));
2019-06-07 08:59:07 +00:00
}
image.Mutate(y => y.Resize(finalWidth, finalHeigth));
thumbnail.Mutate(x => x.DrawImage(image, 1));
2019-06-07 08:59:07 +00:00
}
return thumbnail;
}
public static byte[] SaveToBytes(Image img)
{
2019-08-15 15:08:40 +00:00
using var memoryStream = new MemoryStream();
img.Save(memoryStream, PngFormat.Instance);
2019-08-15 15:08:40 +00:00
return memoryStream.ToArray();
2019-06-07 08:59:07 +00:00
}
public static byte[] SaveToBytes(Image img, IImageFormat imageFormat)
2019-06-07 08:59:07 +00:00
{
byte[] data;
using (var memoryStream = new MemoryStream())
{
img.Save(memoryStream, imageFormat);
2019-06-07 08:59:07 +00:00
data = memoryStream.ToArray();
}
return data;
}
public static string GetImgFormatName(IImageFormat format)
2019-06-07 08:59:07 +00:00
{
return format.Name.ToLower();
2019-06-07 08:59:07 +00:00
}
}
}