How can I resize the images before they are uploaded to the server? RAZOR - C # - WebMatrix [duplicated]

0

What I need is that the images before being uploaded to the server are compressed as much as possible in size in kb or mb, I do not know if this is achieved by changing its size in px before being uploaded, and at the same time Print a pre-defined watermark or label. Since if I left the life-size images the database would fill up very fast and this would bring problems. This project is in C # - RAZOR using Webmatrix.

This is the code that runs when you load the Image:

    if (IsPost  && Request["action"]=="Cargar")
    {
        var numFiles = Request.Files.Count;

        if(numFiles == 0)
        {
            ModelState.AddError("fileUpload", "Selecciona al menos una foto para cargar.");
        } 
        else 
        {



            if(numFiles<=foticos){



            for (int i = 0; i < numFiles; i++)
            {
                var file = Request.Files[i];
var fileExtension2 = Path.GetExtension(file.FileName).Trim();
if(fileExtension2!=".jpg"){

    if(fileExtension2!=".jpeg"){

    if(fileExtension2!=".png"){Response.Redirect(Href("~/MiZona/Panel/Modificar/vehiculos/"+cateforia+"/"+articulius.titulo.Replace(" ","_")+""));}

    }
}
                if (file.ContentLength > 0)
                {
                    var fileUpload = new WebImage(file.InputStream);
                    var fileTitle = Path.GetFileNameWithoutExtension(file.FileName).Trim();
                    if (fileTitle.IsEmpty())
                    {
                        fileTitle = "Sin título";
                    }
                    var fileExtension = Path.GetExtension(file.FileName).Trim();
                    var fileBytes = fileUpload.GetBytes();
                    conexion.Execute(@"INSERT INTO Photos
                        (GalleryId, UserId, Description, FileTitle, FileExtension, ContentType, FileSize, UploadDate, FileContents) VALUES 
                        (@0, @1, @2, @3, @4, @5, @6, @7, @8)", articulius.albumpublicado, WebSecurity.CurrentUserId, "", fileTitle, fileExtension,
                    fileUpload.ImageFormat, fileBytes.Length, DateTime.Now, fileBytes);
                }
            }}else{Response.Redirect("~/MiZona/Panel/Modificar/vehiculos/"+cateforia+"/"+articulius.titulo.Replace(" ","_")+"/?mensaje=Fotos_Incorrectas");}

            conexion.Execute("UPDATE vehiculos SET publicadoArticulo=3 WHERE idvehiculos = '"+cateforia+"'   ");

             Response.Redirect("~/MiZona/Panel/Modificar/vehiculos/"+cateforia+"/"+articulius.titulo.Replace(" ","_")+"/?mensaje=Foto_Actualizada");
        }
    }
    
asked by Atejada 05.09.2017 в 18:12
source

1 answer

0

Personally I use the library of ImageResizer which is quite easy to use. They even have documentation for your specific problem which basically goes like this:

[HttpPost]
public async Task<JsonResult> upload(string id)
{ 
    //Ciclo para trabajar cada archivo
    foreach (string fileKey in HttpContext.Current.Request.Files.Keys) 
    {
        HttpPostedFile file = HttpContext.Current.Request.Files[fileKey];
        if (file.ContentLength <= 0) continue; //Ignorar archivos vacíos.

        ImageResizer.ImageJob i = new ImageResizer.ImageJob(file, "~/uploads/<guid>.<ext>", new ImageResizer.ResizeSettings(
                "width=800;height=600;format=jpg;mode=max")); //Tamaño de 800x600
        i.CreateParentDirectory = true; //Crear el directorio si no existe.
        i.Build();
    }
    ...
}

On the other hand, following the documentation for watermarks ( complementary plugin that you find here ), this can be applied when serving the file; I leave you the link to the full command reference of ImageResizer.

Considering that you are talking about an application of ASP.NET in MVC , you could do it with this code:

/// <summary>
/// Obtiene la imagen basado en el identificador de la misma.
/// </summary>
/// <param name="id">Identificador de la imagen.</param>
/// <param name="w">Ancho de la imagen.</param>
/// <param name="h">Alto de la imagen.</param>
/// <param name="m">Modo de ajuste de la imagen.</param>
/// <param name="wm">Texto de la marca de agua.</param>
/// <returns>Imagen procesada.</returns>
public FileResult GetPic(string id, int w, int h, string m = "pad", string wm = "")
{
    link = new dbLink(System.Web.HttpContext.Current);
    string archivo = "..."; // Esto es suponiendo que lo almacenas físicamente.
    if (System.IO.File.Exists(archivo))
    {
        using (var ms = new MemoryStream())
        {
            ImageResizer.ImageJob j = new ImageResizer.ImageJob();
            j.Source = archivo;
            j.Instructions = new ImageResizer.Instructions(string.Format("width={0}&height={1}&mode={2}&watermark={3}", w, h, m, wm));
            j.Dest = ms;
            var img = ImageResizer.ImageBuilder.Current.Build(j);

            return File(ms.ToArray(), "image/jpg");
        }
    }
    throw new System.Web.HttpException(404, "Imagen no encontrada.");
}
    
answered by 05.09.2017 в 18:54