2010-01-06 5 views
11

Différentes saveurs de cette question ont été posées mais je n'ai pas encore trouvé de réponse correcte. Dites que j'ai une image. Jpg sur le serveur de fichiers et que j'ai besoin d'obtenir sa hauteur et sa largeur. Comment puis-je le faire dans asp.net?ASP.NET: obtenir la hauteur et la largeur d'une image

Je l'ai vu quelques réponses qui suggère de faire quelque chose comme ceci:

System.Drawing.Image image=System.Drawing.Image.FromFile(PicturePath); 
int ActualWidth=image.Width; 
int ActualHeight=image.Height; 
image.Dispose(); 

Cela fonctionnera bien, sauf que classes within the System.Drawing namespace are not supported for use within an ASP.NET service. Alors, comment obtenez-vous la hauteur et la largeur réelles d'une image dans ASP.net?

+1

connexes, mais une autre question: http://stackoverflow.com/questions/390532/system-drawing-in-windows-or-asp-net-services – jball

+1

Image.FromStream (stream, false) chargera la largeur et la hauteur sans analyser toutes les données d'image. Assurez-vous de disposer de l'image suivie par le flux et tout ira bien. L'avertissement est là parce que le programmeur moyen est trop paresseux pour gérer correctement la gestion manuelle de la mémoire. –

Répondre

0

Cela dit Service, pas Application. Cela fonctionnera très bien.

+0

Le processus de travail ASP ne s'exécute pas en tant que service? – jball

+0

http://dotnet.org.za/eduard/archive/2004/09/23/4226.aspx – jball

7

ajouter un contrôle d'image côté serveur sur le ASPX

<asp:image ID="img1" runat="server" src="" /> 

et sur le code donne derrière lui un src

img1.src = System.Drawing.Image.FromFile(PicturePath); 

int ActualWidth = img1.Width; 
int ActualHeight = img1.Height; 
img1.src = ""; 
+0

System.Drawing ne doit pas être utilisé dans ASP.net selon la page MSDN mentionné dans la question. – Anthony

+2

img1.src ne fonctionne pas de toute façon. Vous avez probablement voulu img1.ImageUrl – Anthony

+0

oui exactement cela – Hiyasat

1

Pour éviter d'utiliser l'espace de noms System.Drawing:

Pour GIF, la hauteur et la largeur sont des entiers de 4 octets trouvés dans l'en-tête du fichier. (Adresse 0x12 pour la largeur, la hauteur 0x16)

Pour JPGs, vous pouvez essayer d'écrire une fonction comme celle qui se trouve ici: http://www.64lines.com/jpeg-width-height Il passe dans le JPG comme un tableau de données et obtient la hauteur et la largeur.

+0

Merci mais votre lien ne fonctionne pas. – Anthony

+0

Désolé Anothony, réparé. –

1

mai cette aide

string lPath = Server.MapPath("~\\Images1\\") + dsProd.Tables[0].Rows[i]["Image1"].ToString(); 

Image1.ImageUrl = "Images1\\" + dsProd.Tables[0].Rows[i]["Image1"].ToString(); 
Image2.ImageUrl = "Images1\\" + dsProd.Tables[0].Rows[i]["Image2"].ToString(); 


string currentImagePath = lPath.ToString();// Session["FullImagePath"] + "\\" + GetCurrentFileName(); 
Bitmap bmp = new Bitmap(currentImagePath); 



int iActualWidth=0,iActualHeight=0; 
for (int j = 1; j <= 100; j++) 
{ 
    if ((bmp.Width/j) > 150) 
    { 
      iActualWidth = bmp.Width/j; 
      iActualHeight = bmp.Height/j; 
    } 
    else 
    { 
     break; 
    } 
} 

Image1.Height = new Unit(iActualHeight); 
Image1.Width = new Unit(iActualWidth); 
-1

Importations System.Drawing.Image, System.IO

Dim image As System.Drawing.Image 

image = image.FromFile([filepath]) 

If image.Width > 440 Or image.Height > 440 Then 
'show resized 
else 
'leave as is 
end if 
+1

Quelle est la différence avec le code dans la question? – Anthony

0

J'ai converti le code C++ C# pour référence future:

static bool get_jpeg_size(byte[] data, int data_size, ref int width, ref int height) 
{ 
    //Check for valid JPEG image 
    int i = 0; // Keeps track of the position within the file 
    if (data[i] == 0xFF && data[i + 1] == 0xD8 && data[i + 2] == 0xFF && data[i + 3] == 0xE0) 
    { 
     i += 4; 
     // Check for valid JPEG header (null terminated JFIF) 
     if (data[i + 2] == 'J' && data[i + 3] == 'F' && data[i + 4] == 'I' && data[i + 5] == 'F' && data[i + 6] == 0x00) 
     { 
      //Retrieve the block length of the first block since the first block will not contain the size of file 
      var block_length = data[i] * 256 + data[i + 1]; 
      while (i < data_size) 
      { 
       i += block_length;    //Increase the file index to get to the next block 
       if (i >= data_size) return false; //Check to protect against segmentation faults 
       if (data[i] != 0xFF) return false; //Check that we are truly at the start of another block 
       if (data[i + 1] == 0xC0) 
       {   //0xFFC0 is the "Start of frame" marker which contains the file size 
        //The structure of the 0xFFC0 block is quite simple [0xFFC0][ushort length][uchar precision][ushort x][ushort y] 
        height = data[i + 5] * 256 + data[i + 6]; 
        width = data[i + 7] * 256 + data[i + 8]; 
        return true; 
       } 
       else 
       { 
        i += 2;        //Skip the block marker 
        block_length = data[i] * 256 + data[i + 1]; //Go to the next block 
       } 
      } 
      return false;      //If this point is reached then no size was found 
     } 
     else { return false; }     //Not a valid JFIF string 

    } 
    else { return false; }      //Not a valid SOI header 
} 

UTILISATION:

using (var stream = File.OpenRead(path)) 
{ 
    using (var m = new MemoryStream()) 
    { 
     stream.CopyTo(m); 
     var arr = m.ToArray(); 
     int w = 0, h = 0; 

     get_jpeg_size(arr, arr.Length, ref w, ref h); 
     Console.WriteLine(w + "x" + h); 
    } 
} 
-1
Imports System.IO 

Imports System.Drawing         

Dim sFile As Stream = fuPhoto2.PostedFile.InputStream 

Dim img As System.Drawing.Image = System.Drawing.Image.FromStream(sFile) 

If img.PhysicalDimension.Width > 700 And img.PhysicalDimension.Height > 300 Then 

    strPhotoName = fuPhoto2.FileName 

    fuPhoto2.SaveAs(Server.MapPath("~/Images/") + 
fuPhoto2.FileName)         

Else 

    lblErrMeg2.Text = "Image size must be greater than 700 X 300!" 

    fuPhoto2.Focus() 

    Exit Sub 

End If 
+1

System.Drawing ne doit pas être utilisé dans ASP.net selon la page MSDN mentionnée dans la question. Votre variable "img" est basée dessus. Aussi, quelle serait la différence entre img.PhysicalDimension.Width et img.Width (utilisé dans la question)? – Anthony

1

Vous pouvez utiliser la classe "bitmap".

C#

Bitmap bitmap = new Bitmap(filepath); 

int iWidth = bitmap.Width; 
int iHeight = bitmap.Height; 

VB

Dim bitmap As New Bitmap(filepath) 

Dim iWidth As Integer = bitmap.Width 
Dim iHeight As Integer = bitmap.Height 
0

Importations iTextSharp.text

seulement les outils utilisés lors de la création d'un VFI.

  Dim URel As String 
      URel = "https://......." 

      Dim pic As iTextSharp.text.Image 
      pic = iTextSharp.text.Image.GetInstance(URel) 
      Dim sizee As String 
      sizee = pic.Height 
      SOURR = "<img src='" & URel & "' alt='' />" 
0

J'ai eu mes images dans un listview comme ImageButton et moi avions besoin de leur largeur et la hauteur donc j'ai trouvé la solution ici: http://forums.asp.net/t/1262878.aspx?how+to+get+the+image+width+and+height+argh

et son mon code de travail:

ListViewItem item = e.Item; 
    ImageButton img = item.FindControl("img") as ImageButton; 

    FileStream fs = new FileStream(MapPath(img.ImageUrl) , FileMode.Open, FileAccess.Read, FileShare.Read); 
    System.Drawing.Image dimg = System.Drawing.Image.FromStream(fs); 
    int width = Convert.ToInt32(dimg.Width); 
    int height = Convert.ToInt32(dimg.Height); 

J'espère que cela vous aide

Questions connexes