2023年2月7日 星期二

圖片處理

改變大小

※會轉為 jpeg 格式
public static byte[] resizeImage(byte[] imagearray, int maxsize)
{
using (var ms = new System.IO.MemoryStream(imagearray))
using (var image = (Image)new Bitmap(Image.FromStream(ms)))
{
decimal scale = ((decimal)image.Width) / image.Height;
Size size = default;
if (scale > 1)
{
int w = maxsize;
int h = (int)(w / scale);
size = new Size(w, h);
}
else
{
int h = maxsize;
int w = (int)(h * scale);
size = new Size(w, h);
}
byte[] arr;
Bitmap bmp = new Bitmap(image, size);
using (var ms1 = new System.IO.MemoryStream())
{
bmp.Save(ms1, ImageFormat.Jpeg);
arr = ms1.ToArray();
return arr;
}
}
}

寫入文字

var newBitmap = new Bitmap(image.Width, (int)(image.Height + fontsize));
newBitmap.SetResolution(image.HorizontalResolution, image.VerticalResolution);
using (Graphics graphics = Graphics.FromImage(newBitmap))
{
graphics.Clear(Color.White);
graphics.DrawImage(image, 0, 0);
using (Font font = new Font(fontname, fontsize, GraphicsUnit.Pixel))
{
var size = graphics.MeasureString(text, font);
var rect = new RectangleF(x, y, size.Width, size.Height);
graphics.FillRectangle(Brushes.White, rect);
graphics.DrawString(text, font, Brushes.Blue, new PointF(image.Width / 2 - fontsize * 13 / 3, image.Height - size.Height / 2));
}
}

文字轉圖片

Bitmap bmp = new Bitmap(width, Height);
using (Graphics graphics = Graphics.FromImage(bmp))
using (Font font = new Font(fontname, fontsize))
{
graphics.FillRectangle(new SolidBrush(bgcolor), 0, 0, bmp.Width, bmp.Height);
graphics.DrawString(txt, font, new SolidBrush(fcolor), 0, 0);
graphics.Flush();
}

沒有留言:

自訂權限驗證機制

// 使用 filter [Route("api/[controller]")] [ApiController] [Authorize] [TypeFilter(typeof(CustomAsyncAuthorizationFilter))] public c...