Forum |  HardWare.fr | News | Articles | PC | S'identifier | S'inscrire | Shop Recherche
1224 connectés 

  FORUM HardWare.fr
  Programmation
  C#/.NET managed

  [Résolu] Creer et afficher des thumbnail dynamiquement

 


 Mot :   Pseudo :  
 
Bas de page
Auteur Sujet :

[Résolu] Creer et afficher des thumbnail dynamiquement

n°1617858
the big be​n
Posté le 02-10-2007 à 14:27:23  profilanswer
 

Bonjour,
 
Je voudrait savoir comment je peu afficher dans un ImageButton ou autre (qui me permet la gestion du click) d'afficher un Thumb généré dynamiquement.
J'ai déja ma fonction de création du Thumb qui me renvoi une System.Drawing.Image
 
Mais je ne sais pas apres comment afficher cette Image... Suis je obligé de l'enregistrer sous forme de fichier?
 
D'avance merci
 
Ben


Message édité par the big ben le 02-10-2007 à 16:50:22
mood
Publicité
Posté le 02-10-2007 à 14:27:23  profilanswer
 

n°1617879
MagicBuzz
Posté le 02-10-2007 à 14:53:31  profilanswer
 

En ASP.NET ou application "en lourd" ?
 
Voilà ce que je fais en ASP (code .NET 1.1) :

Code :
  1. using System;
  2. using System.Collections;
  3. using System.Drawing;
  4. using System.Drawing.Imaging;
  5. using System.Drawing.Drawing2D;
  6. using System.IO;
  7. using System.Data;
  8.  
  9. namespace bci
  10. {
  11.     public struct ImageEntry
  12.     {
  13.         public string name;
  14.         public DateTime dte;
  15.         public byte[] pict;
  16.     }
  17.  
  18.     public class ImageCache : ArrayList
  19.     {
  20.         public void AddPict(string name, byte[] pict)
  21.         {
  22.             if (this.Count == 4096)
  23.             {
  24.                 int minIndex = 0;
  25.                 DateTime minDate = DateTime.Now;
  26.  
  27.                 for (int i = 0; i < this.Count; i++)
  28.                 {
  29.                     if (((ImageEntry)this[i]).dte < minDate)
  30.                     {
  31.                         minDate = ((ImageEntry)this[i]).dte;
  32.                         minIndex = i;
  33.                     }
  34.                 }
  35.  
  36.                 this.RemoveAt(minIndex);
  37.             }
  38.  
  39.             ImageEntry ie = new ImageEntry();
  40.             ie.dte = DateTime.Now;
  41.             ie.name = name;
  42.             ie.pict = pict;
  43.             this.Add(ie);
  44.         }
  45.  
  46.         public byte[] GetPict(string name)
  47.         {
  48.             foreach (ImageEntry ie in this)
  49.             {
  50.                 if (ie.name == name)
  51.                 {
  52.                     return ie.pict;
  53.                 }
  54.             }
  55.             return null;
  56.         }
  57.     }
  58.  
  59.     /// <summary>
  60.     /// Summary description for showPict.
  61.     /// </summary>
  62.     public class showThb : System.Web.UI.Page
  63.     {
  64.         private Queries commander;
  65.  
  66.         private const float WIDTH = 128;
  67.         private const float HEIGHT = 96;
  68.  
  69.         private void Page_Load(object sender, System.EventArgs e)
  70.         {
  71.             // Ajouter le code pour bloquer si Session vide !
  72.             if (Session.Count == 0 || Session["login"] == null || Session["typtie"] == null || Session["codsoc"] == null)
  73.             {
  74.                 Session.Clear();
  75.                 Response.Redirect("Default.aspx", true);
  76.             }
  77.  
  78.             // On vérifie que les critères de recherche on bien été remplis
  79.             if (Request.QueryString["chemin_acces"] == null)
  80.             {
  81.                 Session.Clear();
  82.                 Response.Redirect("Default.aspx", true);
  83.             }
  84.  
  85.             if ((string)Request.QueryString["chemin_acces"] != string.Empty)
  86.             {
  87.                 Image thb;
  88.                 byte[] cthb = ((ImageCache)Application["thbCache"]).GetPict((string)Request.QueryString["chemin_acces"]);
  89.                 if (cthb != null)
  90.                 {
  91.                     MemoryStream memStreamc = new MemoryStream();
  92.                     memStreamc.Write(cthb, 0, cthb.Length);
  93.                     thb = Image.FromStream(memStreamc);
  94.                 }
  95.                 else
  96.                 {
  97.                     Image ori = Image.FromFile(MapPath(((string)Request.QueryString["chemin_acces"]).Replace("ap$photo:", @"./MobileCatalogueService/images/" )));
  98.                 
  99.                     thb = new Bitmap((int)WIDTH, (int)HEIGHT);
  100.                     Graphics g = Graphics.FromImage(thb);
  101.                 
  102.                     float oriRatio = (float)ori.Width / (float)ori.Height;
  103.                     float destRatio = WIDTH / HEIGHT;
  104.  
  105.                     float w, h;
  106.  
  107.                     if ((float)ori.Width > WIDTH || (float)ori.Height > HEIGHT)
  108.                     {
  109.                         if (oriRatio >= destRatio)
  110.                         {
  111.                             w = (float)WIDTH;
  112.                             h = (float)ori.Height * (float)WIDTH / (float)ori.Width;
  113.                         }
  114.                         else
  115.                         {
  116.                             h = (float)HEIGHT;
  117.                             w = (float)ori.Width * (float)HEIGHT / (float)ori.Height;
  118.                         }
  119.                     }
  120.                     else
  121.                     {
  122.                         w = (float)ori.Width;
  123.                         h = (float)ori.Height;
  124.                     }
  125.  
  126.                     g.Clear(Color.Transparent);
  127.  
  128.                     float wo = (WIDTH - w) / 2f;
  129.                     float ho = (HEIGHT - h) / 2f;
  130.  
  131.                     g.DrawImage(ori, wo, ho, w, h);
  132.                     byte[] bthb;
  133.                     MemoryStream memStreamb = new MemoryStream();
  134.                     thb.Save(memStreamb, ImageFormat.Png);
  135.                     bthb = memStreamb.ToArray();
  136.                     ((ImageCache)Application["thbCache"]).AddPict(((string) Request.QueryString["chemin_acces"]), bthb);
  137.                     ori.Dispose();
  138.                 }
  139.                 MemoryStream memStream = new MemoryStream();
  140.                 thb.Save(memStream, ImageFormat.Png);
  141.                 thb.Dispose();
  142.  
  143.                 Response.Clear();
  144.                 Response.ContentType="image/png";
  145.  
  146.                 memStream.WriteTo(Response.OutputStream);
  147.             }
  148.             else
  149.             {
  150.                 Image img = new Bitmap(MapPath("medias/sans.jpg" ));
  151.                 MemoryStream memStream = new MemoryStream();
  152.  
  153.                 img.Save(memStream, ImageFormat.Jpeg);
  154.                 img.Dispose();
  155.  
  156.                 Response.Clear();
  157.                 Response.ContentType="image/jpeg";
  158.  
  159.                 memStream.WriteTo(Response.OutputStream);
  160.             }
  161.         }
  162.  
  163.         private void Page_Unload(object sender, System.EventArgs e)
  164.         {
  165.             try{commander.Close();} catch {};
  166.             commander = null;
  167.         }
  168.  
  169.         #region Web Form Designer generated code
  170.         override protected void OnInit(EventArgs e)
  171.         {
  172.             //
  173.             // CODEGEN: This call is required by the ASP.NET Web Form Designer.
  174.             //
  175.             InitializeComponent();
  176.             base.OnInit(e);
  177.         }
  178.         
  179.         /// <summary>
  180.         /// Required method for Designer support - do not modify
  181.         /// the contents of this method with the code editor.
  182.         /// </summary>
  183.         private void InitializeComponent()
  184.         {    
  185.             this.Load += new System.EventHandler(this.Page_Load);
  186.             this.Unload += new System.EventHandler(this.Page_Unload);
  187.         }
  188.         #endregion
  189.     }
  190. }


=> Je passe par un memorystream avant de faire un BinaryWrite de son contenu (je te mets tout, comme ça t'as aussi la gestion du cache :D)
 
Si c'est dans du Windows Forms, je vois pas trop le problème... Tu colles ton objet Image comme image de fond de ton contrôle :??:

n°1617882
the big be​n
Posté le 02-10-2007 à 14:58:10  profilanswer
 

Mais tu n a pas la possibilité de gerer ton click si tu écrit un memory stream, si?
 
Et c est pour faire en ASP.Net 2.0
 
J'essaie de créer un FileManager vu que j ai pas trouvé mon bonheur gratuit


Message édité par the big ben le 02-10-2007 à 14:59:37
n°1617886
MagicBuzz
Posté le 02-10-2007 à 15:00:22  profilanswer
 

Hein ? Quel click ?
 
Ca n'a rien à voir.
 
Là tu génère une image. Après tu la colles dans le contrôle que tu veux... Oublie le HTML. "Image", en C# comme dans n'importe quel langage, c'est du bête affichage, sans aucune interaction avec l'utilisateur autre que visuelle.
 
Si tu veux que ça détecte le click, tu colles ton image dans un picturebox auquel tu associes un handler sur l'event click. Mais ça n'a rien à voir avec l'image elle-même.

n°1617888
MagicBuzz
Posté le 02-10-2007 à 15:03:45  profilanswer
 

PS : Ma page que tu vois, chez moi s'appelle showthb.aspx
 
Ensuite, dans ma page d'affichage des thumbs j'ai ça :
 

Code :
  1. private void bouProListe_ItemDataBound(object sender, RepeaterItemEventArgs e)
  2.         {
  3.                 ((Image)e.Item.FindControl("thb" )).Attributes.Add("alt", (string)((DataRowView)e.Item.DataItem)["nompro"]);
  4.                 if (((string)((DataRowView)e.Item.DataItem)["chemin_acces"]).Trim() != string.Empty)
  5.                 {
  6.                     ((Image)e.Item.FindControl("thb" )).Attributes.Add("onclick", "javascript:window.open(\"Picture.aspx?chemin_acces=" + ((string)((DataRowView)e.Item.DataItem)["chemin_acces"]).Trim().Replace("\\", "\\\\" ) + "\", \"Picture\" )" );
  7.                 }
  8.                 ((Image)e.Item.FindControl("thb" )).ImageUrl = "showThb.aspx?chemin_acces=" + ((string)((DataRowView)e.Item.DataItem)["chemin_acces"]).Trim();
  9.  
  10. [...]


 

Code :
  1. <asp:Repeater Runat="server" ID="bouProListe">
  2.                             <ItemTemplate>
  3.                                 <table class="vignette" border="1" bordercolor="white" cellspacing="0">
  4.                                     <tr>
  5.                                         <td colspan="2" align="center" valign="middle">
  6.                                             <asp:Image Height="96" Width="128" id="thb" Runat="server" /></td>
  7.                                     </tr>
  8.                                     <tr>
  9.                                         <td colspan="2">
  10.                                             <asp:Label ID="nompro" Runat="server"></asp:Label></td>
  11.                                     </tr>
  12. [...]


Message édité par MagicBuzz le 02-10-2007 à 15:04:20
n°1617889
MagicBuzz
Posté le 02-10-2007 à 15:04:43  profilanswer
 

ps : ouais, c'est très goret mais bon, je découvrais à l'époque, et vu que ça marche... :spamafote:

n°1617911
the big be​n
Posté le 02-10-2007 à 15:24:09  profilanswer
 

Bon j essaie de faire un mix entre tes fonctions et les miennes  
 
Il me calcul bien mes tailles mais par contre il n'affiche rien grrrr
 
J'ai donc :

Code :
  1. GetThumbNail(Server.MapPath("~/uploadfile/test_3.jpg" )).WriteTo(Response.OutputStream);


 

Code :
  1. private MemoryStream GetThumbNail(string fileName)
  2.     {
  3.        // Bitmap bmp;
  4.         int imgWidth = Convert.ToInt32(ConfigurationManager.AppSettings["Thumb_height"]);
  5.         int imgHeight = Convert.ToInt32(ConfigurationManager.AppSettings["Thumb_width"]);
  6.         System.Drawing.Image bmp = Bitmap.FromFile(fileName);
  7.         imgWidth = bmp.Width > imgWidth ? imgWidth : bmp.Width;
  8.         imgHeight = bmp.Height > imgHeight ? imgHeight : bmp.Height;
  9.         Bitmap retBmp = new Bitmap(imgWidth, imgHeight, System.Drawing.Imaging.PixelFormat.Format64bppPArgb);
  10.         Graphics grp = Graphics.FromImage(retBmp);
  11.         int tnWidth = imgWidth, tnHeight = imgHeight;
  12.         if (bmp.Width > bmp.Height)
  13.             tnHeight = (int)(((float)bmp.Height / (float)bmp.Width) * tnWidth);
  14.         else if (bmp.Width < bmp.Height)
  15.             tnWidth = (int)(((float)bmp.Width / (float)bmp.Height) * tnHeight);
  16.         int iLeft = (imgWidth / 2) - (tnWidth / 2);
  17.         int iTop = (imgHeight / 2) - (tnHeight / 2);
  18.         grp.PixelOffsetMode = PixelOffsetMode.None;
  19.         grp.InterpolationMode = InterpolationMode.HighQualityBicubic;
  20.         grp.DrawImage(retBmp, iLeft, iTop, tnWidth, tnHeight);
  21.         //Pen pn = new Pen(penColor, 1); //Color.Wheat
  22.         //grp.DrawRectangle(pn, 0, 0, retBmp.Width - 1, retBmp.Height - 1);
  23.         MemoryStream memStreamb = new MemoryStream();
  24.         retBmp.Save(memStreamb, ImageFormat.Bmp);
  25.         return memStreamb;
  26.     }

n°1617919
MagicBuzz
Posté le 02-10-2007 à 15:29:56  profilanswer
 

tu appelles bien ta fonction dans une page vide, qui ne contient rien et donc le content-type est euh... image/bmp (pkoi tu bosses en bmp ? :o)

n°1617924
the big be​n
Posté le 02-10-2007 à 15:34:43  profilanswer
 

Oui oui ma page est completement vide pour l instant
J ai utilisé Bitmap uniquement pcq j ai rassemblé les idée que j ai trouvé sur le net et essayé d en faire une fonction je ne sais pas par quoi remplacer mon Objet Bitmap...
 
Par quoi puis je le remplacer?
 
Je vient de remplacer par:

Code :
  1. private MemoryStream GetThumbNail(string fileName)
  2.     {
  3.        // Bitmap bmp;
  4.         int imgWidth = Convert.ToInt32(ConfigurationManager.AppSettings["Thumb_height"]);
  5.         int imgHeight = Convert.ToInt32(ConfigurationManager.AppSettings["Thumb_width"]);
  6.         System.Drawing.Image bmp = System.Drawing.Image.FromFile(fileName);
  7.         imgWidth = bmp.Width > imgWidth ? imgWidth : bmp.Width;
  8.         imgHeight = bmp.Height > imgHeight ? imgHeight : bmp.Height;
  9.         System.Drawing.Image retBmp = new Bitmap(imgWidth, imgHeight, System.Drawing.Imaging.PixelFormat.Format64bppPArgb);
  10.         Graphics grp = Graphics.FromImage(retBmp);
  11.         int tnWidth = imgWidth, tnHeight = imgHeight;
  12.         if (bmp.Width > bmp.Height)
  13.             tnHeight = (int)(((float)bmp.Height / (float)bmp.Width) * tnWidth);
  14.         else if (bmp.Width < bmp.Height)
  15.             tnWidth = (int)(((float)bmp.Width / (float)bmp.Height) * tnHeight);
  16.         int iLeft = (imgWidth / 2) - (tnWidth / 2);
  17.         int iTop = (imgHeight / 2) - (tnHeight / 2);
  18.         grp.PixelOffsetMode = PixelOffsetMode.None;
  19.         grp.InterpolationMode = InterpolationMode.HighQualityBicubic;
  20.         grp.DrawImage(retBmp, iLeft, iTop, tnWidth, tnHeight);
  21.         //MemoryStream memStreamb = new MemoryStream();
  22.         retBmp.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
  23.         return null;
  24.     }


Message édité par the big ben le 02-10-2007 à 15:39:56
n°1617930
MagicBuzz
Posté le 02-10-2007 à 15:48:15  profilanswer
 

Nan c'était à propos du "ImageFormat.Bmp" ;)
 
Sinon, accessoirement, à moins que tes thb soient carrées, ton test "if (bmp.Width > bmp.Height)" n'est pas bon, il faut passer par test sur le ration width/height à la place.
 
Et essaie de faire un Response.BinaryWrite() plutôt qu'un save dans le outputstream (à mon avis il est écrasé par les méthodes de base)

mood
Publicité
Posté le 02-10-2007 à 15:48:15  profilanswer
 

n°1617952
the big be​n
Posté le 02-10-2007 à 15:58:08  profilanswer
 

oui mais pour l instant si mon image est déformée je m en fout encore pas mal si j ai qq chose se serait déja bien :)
 
Avec mon code précédent j obtient juste en carré noir => bof
 
et idem en mettant  

Code :
  1. MemoryStream memStreamb = new MemoryStream();
  2.         retBmp.Save(memStreamb, System.Drawing.Imaging.ImageFormat.Jpeg);
  3.         Response.BinaryWrite(memStreamb.ToArray());


Message édité par the big ben le 02-10-2007 à 15:59:13
n°1617957
the big be​n
Posté le 02-10-2007 à 16:02:40  profilanswer
 

Ow un miracle!
 
en repartant de ton code:  

Code :
  1. private void GetThumbNail(string fileName)
  2.     {
  3.         int WIDTH = Convert.ToInt32(ConfigurationManager.AppSettings["Thumb_height"]);
  4.         int HEIGHT = Convert.ToInt32(ConfigurationManager.AppSettings["Thumb_width"]);
  5.         System.Drawing.Image thb;
  6.         System.Drawing.Image ori = System.Drawing.Image.FromFile(fileName);
  7.         thb = new Bitmap((int)WIDTH, (int)HEIGHT);
  8.         Graphics g = Graphics.FromImage(thb);
  9.         float oriRatio = (float)ori.Width / (float)ori.Height;
  10.         float destRatio = WIDTH / HEIGHT;
  11.         float w, h;
  12.         if ((float)ori.Width > WIDTH || (float)ori.Height > HEIGHT)
  13.         {
  14.             if (oriRatio >= destRatio)
  15.             {
  16.                 w = (float)WIDTH;
  17.                 h = (float)ori.Height * (float)WIDTH / (float)ori.Width;
  18.             }
  19.             else
  20.             {
  21.                 h = (float)HEIGHT;
  22.                 w = (float)ori.Width * (float)HEIGHT / (float)ori.Height;
  23.             }
  24.         }
  25.         else
  26.         {
  27.             w = (float)ori.Width;
  28.             h = (float)ori.Height;
  29.         }
  30.         g.Clear(Color.Transparent);
  31.         float wo = (WIDTH - w) / 2f;
  32.         float ho = (HEIGHT - h) / 2f;
  33.         g.DrawImage(ori, wo, ho, w, h);
  34.         MemoryStream memStreamb = new MemoryStream();
  35.         thb.Save(memStreamb, ImageFormat.Png);   
  36.         ori.Dispose();
  37.         memStreamb.WriteTo(Response.OutputStream);
  38.     }

n°1617958
MagicBuzz
Posté le 02-10-2007 à 16:03:07  profilanswer
 

déjà, bosse en 32 bits, ça sera suffisant :o
 
ensuite, t'as peut-être simplement un problème avec ton drawimage.
 
commence déjà par :
1/ charger ton image sans la déformer
2/ la dessiner dans une image de la même taille
3/ la coller en binarywrite
 
si ça marche, tu peux commencer à redimensionner
 
mais le mieux c'est de faire étape par étape, ça permet de trouver les erreurs plus facilement ;)

n°1617961
the big be​n
Posté le 02-10-2007 à 16:04:11  profilanswer
 

Et ensuite si je veut inclure le contenu de mon memStreamb dans mon ImageButton parmis d autres controles, il y a moyen ?


Message édité par the big ben le 02-10-2007 à 16:05:15
n°1617968
MagicBuzz
Posté le 02-10-2007 à 16:10:48  profilanswer
 

enregistre ton truc sous le nom de "mapititenimagequivabien.aspx/mapititenimagequivabien.aspx.cs"
 
et dans ta page "mapititelistequivabien.aspx.cs" tu colles un :
 

Code :
  1. monpitiImageButtonQuiVaBien.BackgroundImage = "mapititenimagequivabien.aspx?pict=toto.jpg";


Message édité par MagicBuzz le 02-10-2007 à 16:11:48
n°1617970
MagicBuzz
Posté le 02-10-2007 à 16:12:32  profilanswer
 

(backgroundimage ou je sais plus quelle propriété... celle qui permet d'associer une image à ton bouton quoi...)

n°1617985
the big be​n
Posté le 02-10-2007 à 16:37:10  profilanswer
 

Génial un tout tout grand merci pour ton aide... et ta patience ;)


Aller à :
Ajouter une réponse
  FORUM HardWare.fr
  Programmation
  C#/.NET managed

  [Résolu] Creer et afficher des thumbnail dynamiquement

 

Sujets relatifs
[Résolu] Erreur de collation[résolu] Utilisation de List dans "Yet Another Haskell Tutorial"
Album photos et commentaires[Résolu] Javascript Rajout de td en chaine dans un tableau
afficher valeur checkbox dans champ de saisiereq sql Max(id) + GROUP/[RESOLU]
Créer un script permettant de lister dossier et sous-dossierscreer dossier automatiquement a partir des tags
qui pourrait me creer une intro flash pour mon site ?[RESOLU] Comment faire un echo sans retour chariot sous unix ?
Plus de sujets relatifs à : [Résolu] Creer et afficher des thumbnail dynamiquement


Copyright © 1997-2022 Hardware.fr SARL (Signaler un contenu illicite / Données personnelles) / Groupe LDLC / Shop HFR