Visualizzazione dei risultati da 1 a 4 su 4
  1. #1

    Upload resize qualità thumb

    Ciao a tutti, ho trovato questo codice e funzia

    codice:
    void Page_Load(object sender, System.EventArgs e)
      {
       titletext2.Text = titletext.Text = ""Upload & Resample On-Fly, delle immagini inviate, su di una cartella del Server" [v.1.2.0]";
       Status.Text += "";
      } // void Page_Load(object sender, System.EventArgs e)
      
      
    bool IsImage(string fileName)
    {
      string ext = Path.GetExtension(fileName).ToLower();
      bool imageFlag = false;
    
      if (ext != null)
       {
        switch (ext)
         {
          case ".emf" : // Enhanced Windows metafile image format
          case ".exif" : // Exchangable Image Format
          case ".ico" : // Windows icon image format (extension .ico)
          case ".wmf" : // Windows metafile image format (extension .wmf)
          case ".png" : // Specifies the W3C Portable Network Graphics image format (extension .png)
          case ".gif" : // Graphics Interchange Format image format (extension .gif)
          case ".bmp" : //Bitmap image format (extension .bmp)
          case ".tiff" : // Tag Image File Format (extension .tif)
          case ".tif" : // Tag Image File Format (extension .tif)
          case ".jpeg" : // Joint Photographic Experts Group image format (extensions .jpg, .jpeg)
          case ".jpg" : imageFlag = true; break; // Joint Photographic Experts Group image format (extensions .jpg, .jpeg)
    
          default: imageFlag = false; break;  // Not a supported file type.
         } // switch (ext)
       } // if (ext != null)
      else
       imageFlag = false;
    
      return imageFlag;
    } // bool IsImage(string fileName)
    
    void UploadAndResizeAnImage(HttpPostedFile file, double newWidth, double newHeight, string virPath, bool overwrite)
      {
       string destPath = ".";
       double ThumbnailWidth = 64.0;
       double ThumbnailHeight = 64.0;
       bool owr = false;
       bool exist = false;
    
       if (virPath != "") destPath = virPath;
       if (newWidth > 0) ThumbnailWidth = newWidth;
       if (newHeight > 0) ThumbnailHeight = newHeight;
       if (overwrite)
        owr = true;
       else
        owr = false;
    
       int pathCheck = (destPath.Substring(destPath.LastIndexOf('/') + 1)).Length;
       if (pathCheck > 0) destPath += "/";
    
       string fileName = Path.GetFileName(file.FileName);
       string estensione = Path.GetExtension(file.FileName).ToLower();
       double orgImgWidth = 0.0;
       double orgImgHeight = 0.0;
       double rThumbnailWidth = 0.0;
       double rThumbnailHeight = 0.0;
       
       ImageCodecInfo[] imgCodec = ImageCodecInfo.GetImageEncoders();
       EncoderParameters encPars = new EncoderParameters(2);
       EncoderParameter encPar1 = new EncoderParameter( System.Drawing.Imaging.Encoder.Quality, 100L );
       EncoderParameter encPar2 = new EncoderParameter( System.Drawing.Imaging.Encoder.Compression, 100L );
       
       encPars.Param[0] = encPar1;
       encPars.Param[1] = encPar2;
    
       destPath = Server.MapPath(destPath);
       exist = File.Exists(destPath + fileName);
       
       if (!exist && (fileName.Length != 0) || owr)
        {
         if (!IsImage(fileName))
          {
           if (fileName.Length != 0)
             Status.Text += "<span style=\"color:Red;\">File '" + fileName + "' is not a valid image format. Upload... Aborted.</span>
    ";
           return;
          } // if (!IsImage(fileName))
    
        
         using(System.Drawing.Image image = System.Drawing.Image.FromStream(file.InputStream))
          {
           rThumbnailWidth = ThumbnailWidth;
           rThumbnailHeight = ThumbnailHeight;
           orgImgWidth = image.Width;
           orgImgHeight = image.Height;
           
           // Se l'immagine è più piccola del Thumbnail forziamo le dimensioni di
           // quest'ultimo alle dimensioni dell'immagine.
           if (orgImgWidth < rThumbnailWidth) rThumbnailWidth = image.Width;
           if (orgImgHeight < rThumbnailHeight) rThumbnailHeight = image.Height;
           
           // Se le dimensioni dell'immagine e del Thumbnail corrispondono non facciamo nulla.
           // quindi se l'immagine è quadrata...
           if (image.Width != image.Height)
            {
             // Se l'immagine non è quadrata
             // continuiamo a fare i nostri controlli per calcolarne le
             // giuste dimensioni e quindi creare la nostra nuova immagine con
             // l'aspectratio corretto.
            
             // Se l'immagine è più larga che alta
             if (image.Width > image.Height)
              {
               // L > H => L = tL
               // La larghezza del TN sarà quella da noi stabilita
               // quindi dobbiamo solo assegnarla.
               rThumbnailWidth = rThumbnailWidth;
               // L'altezza del TN invece dovrà essere ricalcolata
               // in proporzione alla larghezza dell'immagine originale.
               // L > H => tH = (H * tL)/ L
               rThumbnailHeight = (double)((image.Height * rThumbnailWidth) / image.Width);
              } // if (tmpImage.Width > tmpImage.Height)
             else
              {
               // Altrimenti se l'immagine è più alta
               if (image.Width < image.Height)
                {
                 // L < H => H = tH
                 // L'altezza del TN sarà quella da noi stabilita
                 // quindi dobbiamo solo assegnarla.
                 rThumbnailHeight = rThumbnailHeight;
                 // La larghezza del TN invece dovrà essere ricalcolata
                 // in proporzione alla altezza dell'immagine originale.
                 // L < H => tL = (L * tH)/ H
                 rThumbnailWidth = (double)((image.Width * rThumbnailHeight) / image.Height);
                } // if (image.Width < image.Height)
              } // else
            } // if (image.Width != image.Height)
    
           using(Bitmap bitmap = new Bitmap(image, (int)(rThumbnailWidth), (int)(rThumbnailHeight)))
            {
             string message = "Uploaded";
             if (exist && owr)
               {
               message = "OverWritted";
               try
                {
                 File.Delete(destPath + fileName);    
                }
               catch(IOException ioe)
                {
                   message = "<div id=\"error\">Error: " + ioe.GetType().Name + ": The write operation could not  be performed because the specified part of the file is locked. Not OverWritted</div>";
                }
              } // if (exist && owr)
    
             if ((estensione == ".jpg") || (estensione == ".jpeg"))
              bitmap.Save(destPath + fileName, imgCodec[1], encPars);
             else
              bitmap.Save(destPath + fileName, image.RawFormat);
    
             Status.Text += "<span style=\"color:Green;\">File '" + fileName + " &#64; [" + (int)(orgImgWidth) + "px X " + (int)(orgImgHeight) + "px]' " + message + " with this new size [" + (int)(rThumbnailWidth) + "px X " + (int)(rThumbnailHeight) + "px]</span>
    ";
            } // using(Bitmap bitmap = new Bitmap(image, (int)(rThumbnailWidth), (int)(rThumbnailHeight)))
          } // using(Image image = Image.FromFile(file))
        } // if (!exist && (fileName.Length != 0) || owr)
       else
        {
         if (exist && (!owr))
            Status.Text += "<span style=\"color:Red;\">Error : The file \"<u>" + fileName + "</u>\" already exist... Upload Aborted.</span>
    ";
        }
      } //  void UploadAndResizeAnImage(HttpPostedFile file, double newWidth, double newHeight, string virPath, bool overwrite)
      
    protected void SubmitButton_Click(Object sender, EventArgs e)
    {
      HttpFileCollection uploadedFiles = Request.Files;
    
      for (int i = 0; i < uploadedFiles.Count; i ++)  
       {
        // Qui sotto definisci le dimensioni che vuoi, la cartella di destinazione
        // e se l'applicazione deve sovrascrivere o no i files preesistenti.
        //
        // UploadAndResizeAnImage(HttpPostedFile file, double newWidth, double newHeight, string virPath, bool overwrite)
        //
        // Quindi  se scrivo come qui sotto :
    
        UploadAndResizeAnImage(uploadedFiles[i], 1024.0, 768.0, "./foto/", true);
        // significa che voglio che ogni immagine inviata (uploadedFiles[i])
        // venga ridimensionata a 1024x768 (tenendo conto però delle proporzioni originali)
        // e che se il file esiste non deve essere sovrascritto (overwrite = false).
        // Chiaro? Più di così ;)
    
        // Vogliamo pure i Thumbnails??? allora aggiungiamo, sempre in questo ciclo for :
        UploadAndResizeAnImage(uploadedFiles[i], 150.0, 150.0, "./miniature/", true);
        // significa che voglio che ogni immagine inviata (uploadedFiles[i])
        // venga ridimensionata a 150x150 (tenendo conto però delle proporzioni originali)
        // e che se il file esiste non deve essere sovrascritto (overwrite = false).
        
       }
       
      Status.Text += "
    <center><pre>Coded by <a href=\"http://forum.html.it/forum/member.php?s=&action=getinfo&userid=83362\" title=\"R.B.Riddick\" target=\"blank\">R.B.Riddick &copy;</a>
     on 
    <a href=\"http://www.html.it\" target=\"_blank\">html.it</a></pre></center>";
      Status.Text += "
    
    <a href=\"http://validator.w3.org/check?uri=referer\" target=\"blank\"><img src=\"http://www.w3.org/Icons/valid-html401\" alt=\"Valid HTML 4.01 Transitional\" height=\"31\" width=\"88\" border=\"0\"></a></p>";
    } // protected void SubmitButton_Click(Object sender,
    Il "problema" è che le thumb non hanno una buona qualità, e non c'entrano i due parametri sulla compressioni/qualità. Credo dipenda dal metodo di resampling. C'è un sistema per ottenere un risultato migliore?

  2. #2
    Ho trovato questa funzione

    codice:
    Bitmap ResizeImage(Stream streamImage, int maxWidth, int maxHeight)
    {
        Bitmap originalImage = new Bitmap(streamImage);
        int newWidth = originalImage.Width;
        int newHeight = originalImage.Height;
        double aspectRatio = (double)originalImage.Width / (double)originalImage.Height;
    
        if (aspectRatio <= 1 && originalImage.Width > maxWidth)
        {
            newWidth = maxWidth;
            newHeight = (int)Math.Round(newWidth / aspectRatio);
        }
        else if (aspectRatio > 1 && originalImage.Height > maxHeight)
        {
            newHeight = maxHeight;
            newWidth = (int)Math.Round(newHeight * aspectRatio);
        }
    
        Bitmap newImage = new Bitmap(originalImage, newWidth, newHeight);
        
        Graphics g = Graphics.FromImage(newImage);
        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBilinear;
        g.DrawImage(originalImage, 0, 0, newImage.Width, newImage.Height);
    
        originalImage.Dispose();
        
        return newImage;     
    }
    Che pensavo di mettere qua

    codice:
       if (!exist && (fileName.Length != 0) || owr)
        {
         if (!IsImage(fileName))
          {
           if (fileName.Length != 0)
             Status.Text += "<span style=\"color:Red;\">File '" + fileName + "' is not a valid image format. Upload... Aborted.</span>
    ";
           return;
          } // if (!IsImage(fileName))
    
        
    	      Bitmap image = ResizeImage(file, newWidth, newHeight);
    	      image.Save(Server.MapPath(virPath) + Guid.NewGuid().ToString() + ".jpg", ImageFormat.Jpeg);
    	      image.Dispose();
    
        } // if (!exist && (fileName.Length != 0) || owr)
    Il problema è che la funzione si aspetta uno stream e io passo un file, come si potrebbe adattare resizeImage per passargli il file?

  3. #3
    Utente di HTML.it L'avatar di cassano
    Registrato dal
    Aug 2004
    Messaggi
    3,002
    Scusate la domanda ma quando si fa :

    Bitmap newImage = new Bitmap(originalImage, newWidth, newHeight)

    si crea una nuova Bitmap con dentro la originalImage (quindi l'immagine vera e propria) ?? oppure soltanto con le caratteristiche richieste ,altezza ,profondità colore ecc... ??

  4. #4
    Ok, ci sono riuscito

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2025 vBulletin Solutions, Inc. All rights reserved.