دسته بندی ها
19:07 1399/12/08

تغییر سایز تصویر در Asp.net core در هنگام آپلود

مشخصات سوال کننده :
کاربر : sunboyali     امتیاز کاربر : 21     رتبه کاربر : 31
دسته بندی : Asp.net Core

به این سوال امتیاز بدهید    0
تعداد بازدید این سوال : 3189
هوش مصنوعی

پاسخ هوش مصنوعی

برای تغییر سایز تصویر در ASP.NET Core 3.1 می توانید از پکیج SixLabors.ImageSharp استفاده کنید. این پکیج امکاناتی برای پردازش تصاویر، از جمله تغییر اندازه، برش، و ... را فراهم می کند. در زیر آموزشی کوتاه برای انجام این کار آورده شده است.

ابتدا، پکیج SixLabors.ImageSharp را به پروژه خود اضافه کنید. این کار را می توانید از طریق کامند لاین با استفاده از NuGet انجام دهید:

dotnet add package SixLabors.ImageSharp

سپس، می توانید از کد زیر برای تغییر اندازه تصویر استفاده کنید:

using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Processing;
using Microsoft.AspNetCore.Http;
using System.IO;
using System.Threading.Tasks;

public class ImageService
{
    public async Task ResizeImage(IFormFile file, int width, int height)
    {
        if (file == null || file.Length == 0)
            return;

        using (var image = await Image.LoadAsync(file.OpenReadStream()))
        {
            image.Mutate(x => x.Resize(width, height));
            var outputPath = Path.Combine("wwwroot/images", file.FileName);

            await image.SaveAsync(outputPath);
        }
    }
}

در این کد، ابتدا تصویر بارگذاری شده را با استفاده از Image.LoadAsync می خوانیم. سپس با استفاده از image.Mutate و x.Resize اندازه تصویر را تغییر می دهیم. در نهایت، تصویر تغییر اندازه داده شده را در مسیر مشخص شده ذخیره می کنیم.

شما می توانید این تابع را در کنترلر خود قرار داده و به آن پارامترهای اندازه ای که می خواهید را نیز ارسال کنید.

به این پاسخ امتیاز بدهید    0
امتیاز: - رتبه: -
پاسخ دهنده : fateme 00:12 1399/12/09

یک کلاس به نام ImageResizer ایجاد کنید و کد زیر رو توش کپی و پیست کنید. دقت کنید که کلاس ImageResizer یک سازنده یا Constructor داره که دو تا ورودی x و y رو دریافت می کنه. این دو مقدار همون طول و عرض جدید تصویر شما خواهند بود. بنابراین هر جایی که از این کلاس یک نمونه ایجاد کردید باید طول و عرض رو هم مشخص کنید تا تصویری با همون اندازه به شما بده. این کد رو در Asp.net Core 5 تست کردم مشکلی نداشت. در نسخه Core 3 هم مشکلی نداره.

 

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Threading.Tasks;

namespace DynamicMenuInCore
{
    public class ImageResizer
    {
        /// <summary>
        /// http://www.blackbeltcoder.com/Articles/graph/programmatically-resizing-an-image
        /// Maximum width of resized image.
        /// </summary>
        public int MaxX { get; set; }

        /// <summary>
        /// Maximum height of resized image.
        /// </summary>
        public int MaxY { get; set; }

        /// <summary>
        /// If true, resized image is trimmed to exactly fit
        /// maximum width and height dimensions.
        /// </summary>
        public bool TrimImage { get; set; }

        /// <summary>
        /// Format used to save resized image.
        /// </summary>
        public ImageFormat SaveFormat { get; set; }

        /// <summary>
        /// Constructor.
        /// </summary>
        public ImageResizer(int x, int y)
        {
            MaxX = x;
            MaxY = y;
            TrimImage = false;
            SaveFormat = ImageFormat.Jpeg;
        }

        /// <summary>
        /// Resizes the image from the source file according to the
        /// current settings and saves the result to the targe file.
        /// </summary>
        /// <param name="source">Path containing image to resize</param>
        /// <param name="target">Path to save resized image</param>
        /// <returns>True if successful, false otherwise.</returns>
        public bool Resize(string source, string target)
        {
            using (Image src = Image.FromFile(source, true))
            {
                // Check that we have an image
                if (src != null)
                {
                    int origX, origY, newX, newY;
                    int trimX = 0, trimY = 0;

                    // Default to size of source image
                    newX = origX = src.Width;
                    newY = origY = src.Height;

                    // Does image exceed maximum dimensions?
                    if (origX > MaxX || origY > MaxY)
                    {
                        // Need to resize image
                        if (TrimImage)
                        {
                            // Trim to exactly fit maximum dimensions
                            double factor = Math.Max((double)MaxX / (double)origX,
                                (double)MaxY / (double)origY);
                            newX = (int)Math.Ceiling((double)origX * factor);
                            newY = (int)Math.Ceiling((double)origY * factor);
                            trimX = newX - MaxX;
                            trimY = newY - MaxY;
                        }
                        else
                        {
                            // Resize (no trim) to keep within maximum dimensions
                            double factor = Math.Min((double)MaxX / (double)origX,
                                (double)MaxY / (double)origY);
                            newX = (int)Math.Ceiling((double)origX * factor);
                            newY = (int)Math.Ceiling((double)origY * factor);
                        }
                    }

                    // Create destination image
                    using (System.Drawing.Image dest = new Bitmap(newX - trimX, newY - trimY))
                    {
                        Graphics graph = Graphics.FromImage(dest);
                        graph.InterpolationMode =
                            System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                        graph.DrawImage(src, -(trimX / 2), -(trimY / 2), newX, newY);
                        dest.Save(target, SaveFormat);
                        // Indicate success
                        return true;
                    }
                }
            }
            // Indicate failure
            return false;
        }
    }
}

 

به این پاسخ امتیاز بدهید    0
امتیاز: 1635 رتبه: 2
برای ارسال پاسخ لطفا وارد حساب کاربری خود شوید.   ورود