Как сжать / изменить размер и отобразить видео в представлении - PullRequest
0 голосов
/ 18 января 2019

Я отображаю изображения и видео в качестве эскиза на странице просмотра. Всякий раз, когда пользователь загружает изображение или видео, я сохраняю URL в БД и файлы в папку. При отображении я изменяю размер изображения на стороне сервера, чтобы уменьшить время загрузки страницы. Я могу сжимать изображения, но не видео. Как изменить размер или сжать видео так же, как изображение. В настоящее время видео не отображается, поскольку используется одна и та же логика для извлечения изображения и видео.

Просмотр:

enter image description here

База данных:

enter image description here

ImageHandler.ashx.cs:

namespace ResoucesProject
{
public class ImageHandler : IHttpHandler
{
    public bool IsReusable
    {
        get { return true; }
    }

    public void ProcessRequest(HttpContext context)
    {
        var fileName = ConfigurationManager.AppSettings["BasePath"] + context.Request.QueryString["file"];
        var filePath = context.Server.MapPath(fileName);
        var fileWidth = 300;
        if (!string.IsNullOrEmpty(context.Request.QueryString["width"]))
        {
            int tempWidth;
            if (int.TryParse(context.Request.QueryString["width"], out tempWidth) && tempWidth < 3000) // set a max limit so people don't request huge files
                fileWidth = tempWidth;
        }

        var fileHeight = 300;
        if (!string.IsNullOrEmpty(context.Request.QueryString["height"]))
        {
            int tempHeight;
            if (int.TryParse(context.Request.QueryString["height"], out tempHeight) && tempHeight < 3000) // set a max limit so people don't request huge files
                fileHeight = tempHeight;
        }

        context.Response.AddHeader("content-disposition",
             string.Format("attachment; filename={0}", fileName));

        if (File.Exists(filePath))
        {
            var buffer = GetResizedImage(filePath, fileWidth, fileHeight);
            if (buffer == null)
            {
                return;
            }

            context.Response.OutputStream.Write(buffer, 0, buffer.Length);
            context.Response.End();
            byte[] bytes = File.ReadAllBytes(filePath);
            context.Response.BinaryWrite(bytes);
        }
        else
        {
            throw new HttpException(404, "Invalid photo name.");
        }
    }

    private static byte[] GetResizedImage(string path, int width, int height)
    {
        try
        {
            var imgIn = new Bitmap(path);
            double y = imgIn.Height;
            double x = imgIn.Width;
            double factor = 1;
            if (width > 0)
            {
                factor = width / x;
            }
            else if (height > 0)
            {
                factor = height / y;
            }
            var outStream = new MemoryStream();
            var imgOut = new Bitmap((int)(x * factor), (int)(y * factor));

            // Set DPI of image (xDpi, yDpi)
            imgOut.SetResolution(72, 72);

            var g = Graphics.FromImage(imgOut);
            g.Clear(Color.White);
            g.DrawImage(imgIn, new Rectangle(0, 0, (int)(factor * x), (int)(factor * y)),
              new Rectangle(0, 0, (int)x, (int)y), GraphicsUnit.Pixel);

            imgOut.Save(outStream, GetImageFormat(path));
            return outStream.ToArray();
        }
        catch (ArgumentException e)
        {
            Console.WriteLine(e.Message);
            return null;
        }

    }

    private static ImageFormat GetImageFormat(string path)
    {
        switch (Path.GetExtension(path))
        {
            case ".bmp": return ImageFormat.Bmp;
            case ".gif": return ImageFormat.Gif;
            case ".jpg": return ImageFormat.Jpeg;
            case ".png": return ImageFormat.Png;
        }
        return ImageFormat.Jpeg;
    }
}

}

Просмотр:

@foreach (var item in Model)
                        {
                            <tr>
                                <td>
                                    <img src="~/ImageHandler.ashx?file=@Html.DisplayFor(modelItem =>item.image_url)&width=100&height=100" style="width:100px; height:100px;" />
                                </td>
                                                              
                            </tr>
                        }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...