ASP.net image resizing

  • itHighway
  • Newbie
  • Newbie
  • No Avatar
  • Inscription: Jan 27, 2008
  • Messages: 7
  • Status: Offline

Message Avril 4th, 2008, 9:37 pm

Bonjour,

Je suis à la recherche de script asp.net qui peut:

- Redimensionner la largeur et la hauteur de l'image donnée
- Enregistrer sur le disque image redimensionnée.
- Le nom de l'image doit être redimensionnée [nom de l'image] _T.jpg


S'il vous plaît conseils.


Merci,
  • Anonymous
  • Bot
  • No Avatar
  • Inscription: 25 Feb 2008
  • Messages: ?
  • Loc: Ozzuland
  • Status: Online

Message Avril 4th, 2008, 9:37 pm

  • righteous_trespasser
  • Scuffle
  • Genius
  • Avatar de l’utilisateur
  • Inscription: Mar 12, 2007
  • Messages: 6228
  • Loc: South-Africa
  • Status: Offline

Message Avril 6th, 2008, 11:28 pm

Ceci est une page qui fait exactement cela...vous pouvez définir la taille maximale de l'image (largeur et hauteur), puis il enregistre à la fois l'original et celui redimensionnés sur le serveur...
Code: [ Select ]
<%@ Page Trace="False" Language="vb" aspcompat="false" debug="true" validateRequest="false"%>
<%@ Import Namespace=System.Drawing %>
<%@ Import Namespace=System.Drawing.Imaging %>
<%@ Import Namespace=System %>
<%@ Import Namespace=System.Web %>
<SCRIPT LANGUAGE="VBScript" runat="server">
    Const Lx = 173 ' max width for thumbnails
    Const Ly = 234 ' max height for thumbnails
    Const upload_dir = "images/" ' directory to upload file
    Const upload_original = "big" ' filename to save original as (suffix added by script)
    Const upload_thumb = "small" ' filename to save thumbnail as (suffix added by script)
    Const upload_max_size = 5000 ' max size of the upload (KB) note: this doesn't override any server upload limits
    Dim fileExt ' used to store the file extension (saves finding it mulitple times)
    Dim newWidth, newHeight As Integer ' new width/height for the thumbnail
    Dim l2 ' temp variable used when calculating new size
    Dim fileFld As HttpPostedFile ' used to grab the file upload from the form
    Dim originalimg As System.Drawing.Image ' used to hold the original image
    Dim msg ' display results
    Dim upload_ok As Boolean ' did the upload work ?
</script>


<%
    Randomize() ' used to help the cache-busting on the preview images
    upload_ok = False
    If LCase(Request.ServerVariables("REQUEST_METHOD")) = "post" Then
        fileFld = Request.Files(0) ' get the first file uploaded from the form (note:- you can use this to itterate through more than one image)
        If fileFld.ContentLength > upload_max_size * 1024 Then
            msg = "Sorry, the image must be less than " & upload_max_size & "Kb"
        Else
            Try
                originalimg = System.Drawing.Image.FromStream(fileFld.InputStream)
                ' work out the width/height for the thumbnail. Preserve aspect ratio and honour max width/height
                ' Note: if the original is smaller than the thumbnail size it will be scaled up
                If (originalimg.Width / Lx) > (originalimg.Width / Ly) Then
                    l2 = originalimg.Width
                    newWidth = Lx
                    newHeight = originalimg.Height * (Lx / l2)
                    If newHeight > Ly Then
                        newWidth = newWidth * (Ly / newHeight)
                        newHeight = Ly
                    End If
                Else
                    l2 = originalimg.Height
                    newHeight = Ly
                    newWidth = originalimg.Width * (Ly / l2)
                    If newWidth > Lx Then
                        newHeight = newHeight * (Lx / newWidth)
                        newWidth = Lx
                    End If
                End If
                Dim thumb As New Bitmap(newWidth, newHeight)
                'Create a graphics object
                Dim gr_dest As Graphics = Graphics.FromImage(thumb)
                ' just in case it's a transparent GIF force the bg to white
                Dim sb = New SolidBrush(System.Drawing.Color.White)
                gr_dest.FillRectangle(sb, 0, 0, thumb.Width, thumb.Height)
                'Re-draw the image to the specified height and width
                gr_dest.DrawImage(originalimg, 0, 0, thumb.Width, thumb.Height)
                Try
                    fileExt = System.IO.Path.GetExtension(fileFld.FileName).ToLower()
                    originalimg.Save(Server.MapPath(upload_dir & TextBoxFileName.Text.ToString & "-" & upload_original & fileExt), originalimg.RawFormat)
                    thumb.Save(Server.MapPath(upload_dir & TextBoxFileName.Text.ToString & "-" & upload_thumb & fileExt), originalimg.RawFormat)
                    msg = "Uploaded " & fileFld.FileName & " to " & Server.MapPath(upload_dir & upload_original & fileExt)
                    upload_ok = True
                Catch ex As Exception
                    msg = "Sorry, there was a problem saving the image."
                End Try
                ' Housekeeping for the generated thumbnail
                If Not thumb Is Nothing Then
                    thumb.Dispose()
                    thumb = Nothing
                End If
            Catch
                msg = "Sorry, that was not an image we could process."
            End Try
        End If
        ' House Keeping !
        If Not originalimg Is Nothing Then
            originalimg.Dispose()
            originalimg = Nothing
        End If
    End If
%>
<html>
<head>
<title>ASP.NET File Upload and Resize Sample</title>
<META NAME="Description" CONTENT="ASP.NET File Upload and Resize Sample (Hybrid VB.NET)">
<META NAME="Keywords" CONTENT="ASP.NET, ASP, NET, VB, VBScript, Image, Upload, Resize, Thumbnail, Constrain, Filesize, File, Size, Free">
<META NAME="Copyright" CONTENT="Rufan-Redi Pty Ltd 2005">
<META NAME="Author" CONTENT="System developed by Jeremy at http://www.Rufan-Redi.com">
</head>
<body>

<p><b>Hybrid ASP.NET File Upload and Resize Sample (VB.NET)</b>
<br>Upload and resize a GIP/JPG/PNG images, ensuring filesizes are optimum.</p>

<form id="Form1" enctype="multipart/form-data" method="post" runat="server">
<table>
<tr><td>Select the file to upload:</td><td><input type="file" name="upload_file"></td></tr>
    <tr>
        <td colspan="2" style="height: 19px">
            New FileName:
            <asp:TextBox ID="TextBoxFileName" runat="server"></asp:TextBox></td>
    </tr>
<tr><td colspan=2>Max upload size <%=upload_max_size%>Kb, gif/jpg/png only. The image will be saved as&nbsp; "New FileName-small" and
    "New FileName-big" accordingly. Just make sure that the original image is 260px
    x 351px big</td></tr>
<tr><td colspan=2><input type="submit" value="Upload" id="Submit1" language="javascript" onclick="return Submit1_onclick()">
</table>
</form>

<%
    If upload_ok Then
%>
<table>
<tr>
<td valign=top><img src="<%=upload_dir & TextBoxFileName.Text.ToString & "-" & upload_original & fileExt & "?" & rnd()%>"></td>
<td valign=top><img src="<%=upload_dir & TextBoxFileName.Text.ToString & "-" & upload_thumb & fileExt & "?" & rnd()%>"></td>
</tr>
</table>
<%
Else
    Response.Write(msg)
End If
%>
</body>
</html>
  1. <%@ Page Trace="False" Language="vb" aspcompat="false" debug="true" validateRequest="false"%>
  2. <%@ Import Namespace=System.Drawing %>
  3. <%@ Import Namespace=System.Drawing.Imaging %>
  4. <%@ Import Namespace=System %>
  5. <%@ Import Namespace=System.Web %>
  6. <SCRIPT LANGUAGE="VBScript" runat="server">
  7.     Const Lx = 173 ' max width for thumbnails
  8.     Const Ly = 234 ' max height for thumbnails
  9.     Const upload_dir = "images/" ' directory to upload file
  10.     Const upload_original = "big" ' filename to save original as (suffix added by script)
  11.     Const upload_thumb = "small" ' filename to save thumbnail as (suffix added by script)
  12.     Const upload_max_size = 5000 ' max size of the upload (KB) note: this doesn't override any server upload limits
  13.     Dim fileExt ' used to store the file extension (saves finding it mulitple times)
  14.     Dim newWidth, newHeight As Integer ' new width/height for the thumbnail
  15.     Dim l2 ' temp variable used when calculating new size
  16.     Dim fileFld As HttpPostedFile ' used to grab the file upload from the form
  17.     Dim originalimg As System.Drawing.Image ' used to hold the original image
  18.     Dim msg ' display results
  19.     Dim upload_ok As Boolean ' did the upload work ?
  20. </script>
  21. <%
  22.     Randomize() ' used to help the cache-busting on the preview images
  23.     upload_ok = False
  24.     If LCase(Request.ServerVariables("REQUEST_METHOD")) = "post" Then
  25.         fileFld = Request.Files(0) ' get the first file uploaded from the form (note:- you can use this to itterate through more than one image)
  26.         If fileFld.ContentLength > upload_max_size * 1024 Then
  27.             msg = "Sorry, the image must be less than " & upload_max_size & "Kb"
  28.         Else
  29.             Try
  30.                 originalimg = System.Drawing.Image.FromStream(fileFld.InputStream)
  31.                 ' work out the width/height for the thumbnail. Preserve aspect ratio and honour max width/height
  32.                 ' Note: if the original is smaller than the thumbnail size it will be scaled up
  33.                 If (originalimg.Width / Lx) > (originalimg.Width / Ly) Then
  34.                     l2 = originalimg.Width
  35.                     newWidth = Lx
  36.                     newHeight = originalimg.Height * (Lx / l2)
  37.                     If newHeight > Ly Then
  38.                         newWidth = newWidth * (Ly / newHeight)
  39.                         newHeight = Ly
  40.                     End If
  41.                 Else
  42.                     l2 = originalimg.Height
  43.                     newHeight = Ly
  44.                     newWidth = originalimg.Width * (Ly / l2)
  45.                     If newWidth > Lx Then
  46.                         newHeight = newHeight * (Lx / newWidth)
  47.                         newWidth = Lx
  48.                     End If
  49.                 End If
  50.                 Dim thumb As New Bitmap(newWidth, newHeight)
  51.                 'Create a graphics object
  52.                 Dim gr_dest As Graphics = Graphics.FromImage(thumb)
  53.                 ' just in case it's a transparent GIF force the bg to white
  54.                 Dim sb = New SolidBrush(System.Drawing.Color.White)
  55.                 gr_dest.FillRectangle(sb, 0, 0, thumb.Width, thumb.Height)
  56.                 'Re-draw the image to the specified height and width
  57.                 gr_dest.DrawImage(originalimg, 0, 0, thumb.Width, thumb.Height)
  58.                 Try
  59.                     fileExt = System.IO.Path.GetExtension(fileFld.FileName).ToLower()
  60.                     originalimg.Save(Server.MapPath(upload_dir & TextBoxFileName.Text.ToString & "-" & upload_original & fileExt), originalimg.RawFormat)
  61.                     thumb.Save(Server.MapPath(upload_dir & TextBoxFileName.Text.ToString & "-" & upload_thumb & fileExt), originalimg.RawFormat)
  62.                     msg = "Uploaded " & fileFld.FileName & " to " & Server.MapPath(upload_dir & upload_original & fileExt)
  63.                     upload_ok = True
  64.                 Catch ex As Exception
  65.                     msg = "Sorry, there was a problem saving the image."
  66.                 End Try
  67.                 ' Housekeeping for the generated thumbnail
  68.                 If Not thumb Is Nothing Then
  69.                     thumb.Dispose()
  70.                     thumb = Nothing
  71.                 End If
  72.             Catch
  73.                 msg = "Sorry, that was not an image we could process."
  74.             End Try
  75.         End If
  76.         ' House Keeping !
  77.         If Not originalimg Is Nothing Then
  78.             originalimg.Dispose()
  79.             originalimg = Nothing
  80.         End If
  81.     End If
  82. %>
  83. <html>
  84. <head>
  85. <title>ASP.NET File Upload and Resize Sample</title>
  86. <META NAME="Description" CONTENT="ASP.NET File Upload and Resize Sample (Hybrid VB.NET)">
  87. <META NAME="Keywords" CONTENT="ASP.NET, ASP, NET, VB, VBScript, Image, Upload, Resize, Thumbnail, Constrain, Filesize, File, Size, Free">
  88. <META NAME="Copyright" CONTENT="Rufan-Redi Pty Ltd 2005">
  89. <META NAME="Author" CONTENT="System developed by Jeremy at http://www.Rufan-Redi.com">
  90. </head>
  91. <body>
  92. <p><b>Hybrid ASP.NET File Upload and Resize Sample (VB.NET)</b>
  93. <br>Upload and resize a GIP/JPG/PNG images, ensuring filesizes are optimum.</p>
  94. <form id="Form1" enctype="multipart/form-data" method="post" runat="server">
  95. <table>
  96. <tr><td>Select the file to upload:</td><td><input type="file" name="upload_file"></td></tr>
  97.     <tr>
  98.         <td colspan="2" style="height: 19px">
  99.             New FileName:
  100.             <asp:TextBox ID="TextBoxFileName" runat="server"></asp:TextBox></td>
  101.     </tr>
  102. <tr><td colspan=2>Max upload size <%=upload_max_size%>Kb, gif/jpg/png only. The image will be saved as&nbsp; "New FileName-small" and
  103.     "New FileName-big" accordingly. Just make sure that the original image is 260px
  104.     x 351px big</td></tr>
  105. <tr><td colspan=2><input type="submit" value="Upload" id="Submit1" language="javascript" onclick="return Submit1_onclick()">
  106. </table>
  107. </form>
  108. <%
  109.     If upload_ok Then
  110. %>
  111. <table>
  112. <tr>
  113. <td valign=top><img src="<%=upload_dir & TextBoxFileName.Text.ToString & "-" & upload_original & fileExt & "?" & rnd()%>"></td>
  114. <td valign=top><img src="<%=upload_dir & TextBoxFileName.Text.ToString & "-" & upload_thumb & fileExt & "?" & rnd()%>"></td>
  115. </tr>
  116. </table>
  117. <%
  118. Else
  119.     Response.Write(msg)
  120. End If
  121. %>
  122. </body>
  123. </html>
Let's leave all our *plum* where it is and go live in the jungle ...
  • rtorres
  • Born
  • Born
  • No Avatar
  • Inscription: Mai 10, 2011
  • Messages: 2
  • Status: Offline

Message Mai 10th, 2011, 4:33 pm

Je sais qu'il s'agit de quelques années, mais peut être que quelqu'un peut nous éclairer sur ce point pour moi.

J'ai été à la recherche de quelque chose comme ça pendant un certain temps. J'ai essayé ceci et obtenez:
Quote:
La page ne peut pas être affichée
La page que vous recherchez ne peut pas être affichée car une méthode non valide (HTTP verbe) a été utilisé pour tentative d'accès.
-------------------------------------------------- ------------------------------

S'il vous plaît essayez les solutions suivantes:

Contactez l'administrateur du site Web si vous pensez que cette demande devrait être autorisée.
Assurez-vous que l'adresse du site Web affichée dans la barre d'adresse de votre navigateur est correctement orthographié et formaté.
Erreur HTTP 405 - Le verbe HTTP utilisé pour accéder à cette page n'est pas autorisé.
Internet Information Services (IIS)



J'ai tenté de mettre sur la page au format HTML, ASP, la mise verbes dans IIS pour html, htm, asp avec tous les accès pour chacun. J'ai mis le script exécutable et l'accès, premissions iis grande ouverte sur le dossier image et le répertoire virtuel. J'ai aussi essayé d'exécuter la racine du site et a également créé le répertoire virtuel. Que suis-je manque ici?
  • nathanaeljones
  • Born
  • Born
  • No Avatar
  • Inscription: Mai 27, 2011
  • Messages: 2
  • Status: Offline

Message Mai 27th, 2011, 1:15 pm

Quelle version de IIS utilisez-vous ? IIS7 a changé en ce qui concerne comment les verbes sont autorisés et refusées.

ID comme de mentionner :

L'extrait de code ci-dessus est défectueux et produira des résultats ugly puisqu'il utilise plus proche voisin d'échantillonnage au lieu de bicubique. Google « Pièges redimensionnement Image » pour plus d'info.

ID suggère d'utiliser quelque chose d'un peu plus mature et bien testé.

Il y a une bibliothèque de Drop-in 120 ko (à imageresizing .net) qui vous permet de télécharger et de redimensionner les images facilement.

Heres un exemple que vous pouvez déposer dans n'importe quelle page avec téléchargement des contrôles. Il redimensionne les images téléchargées tout à 1024 x 768 et les convertit au format JPEG.

Vous pouvez également des cultures et redimensionner un ratio: à l'aide de "largeur = 1024 &amp; hauteur = 768 &amp; crop = auto" serait automatiquement rogner les bords à rendre compatibles les proportions, avec l'image redimensionnez ensuite à 1024 x 768.

Vous pouvez faire pivoter (et faire pivoter = 45), ajouter le padding, ajouter des filigranes et de faire toutes sortes de choses cool aussi bien - son extrêmement flexibles.

Notez que vous pouvez redimensionner même après téléchargement avec ce module - juste ajouter? largeur = 400 et hauteur = 300 dans l'URL de la &lt; img src = "" / &gt; tag.

Code: [ Select ]
//Loop through each uploaded file
foreach (string fileKey in HttpContext.Current.Request.Files.Keys) {
  HttpPostedFile file = HttpContext.Current.Request.Files[fileKey];

  //Get the physical path for the uploads folder
  string uploadFolder = MapPath("~/uploads");

  //Create the upload folder if it is missing
  if (!Directory.Exists(uploadFolder)) Directory.CreateDirectory(uploadFolder);

  //The resizing settings can specify any of 30 commands.. See imageresizing .net for details.
  ResizeSettings resizeCropSettings = new ResizeSettings("maxwidth=1024&maxheight=768&format=jpg");

  //Generate a filename (GUIDs are safest).
  string fileName = Path.Combine(uploadFolder, System.Guid.NewGuid().ToString());

  //What final type of file will we have? This can depend on whether the resizeCropSettings sepcifies a format,
  // and what the original format was (if resizecropSettings doesn't specify one)
  fileName += "." + ImageBuilder.Current.EncoderProvider.GetEncoder(resizeCropSettings, fileUpload.PostedFile.FileName).Extension;

  //Resize the image
  ImageBuilder.Current.Build(file, fileName, resizeCropSettings);
}
  1. //Loop through each uploaded file
  2. foreach (string fileKey in HttpContext.Current.Request.Files.Keys) {
  3.   HttpPostedFile file = HttpContext.Current.Request.Files[fileKey];
  4.   //Get the physical path for the uploads folder
  5.   string uploadFolder = MapPath("~/uploads");
  6.   //Create the upload folder if it is missing
  7.   if (!Directory.Exists(uploadFolder)) Directory.CreateDirectory(uploadFolder);
  8.   //The resizing settings can specify any of 30 commands.. See imageresizing .net for details.
  9.   ResizeSettings resizeCropSettings = new ResizeSettings("maxwidth=1024&maxheight=768&format=jpg");
  10.   //Generate a filename (GUIDs are safest).
  11.   string fileName = Path.Combine(uploadFolder, System.Guid.NewGuid().ToString());
  12.   //What final type of file will we have? This can depend on whether the resizeCropSettings sepcifies a format,
  13.   // and what the original format was (if resizecropSettings doesn't specify one)
  14.   fileName += "." + ImageBuilder.Current.EncoderProvider.GetEncoder(resizeCropSettings, fileUpload.PostedFile.FileName).Extension;
  15.   //Resize the image
  16.   ImageBuilder.Current.Build(file, fileName, resizeCropSettings);
  17. }
  • rtorres
  • Born
  • Born
  • No Avatar
  • Inscription: Mai 10, 2011
  • Messages: 2
  • Status: Offline

Message Juin 16th, 2011, 11:45 am

Désolé pour réponse longtemps retardée. Je suis exécutant IIS 6.0 sur Win Server 2003 SP2
  • nathanaeljones
  • Born
  • Born
  • No Avatar
  • Inscription: Mai 27, 2011
  • Messages: 2
  • Status: Offline

Message Juin 16th, 2011, 12:52 pm

rtorres a écrit:
Désolé pour réponse longtemps retardée. Je suis exécutant IIS 6.0 sur Win Server 2003 SP2


Dans IIS6, vous devriez être capable d'éditer les mappages d'extension - Assurez-vous que POST et GET sont autorisés.

Afficher de l'information

  • Total des messages de ce sujet: 6 messages
  • Utilisateurs parcourant ce forum: Aucun utilisateur enregistré et 170 invités
  • Vous ne pouvez pas poster de nouveaux sujets
  • Vous ne pouvez pas répondre aux sujets
  • Vous ne pouvez pas éditer vos messages
  • Vous ne pouvez pas supprimer vos messages
  • Vous ne pouvez pas joindre des fichiers
 
 

© 2011 Unmelted, LLC. Ozzu® est une marque déposée de Unmelted, LLC