ASP.NET:获取图像的高度和宽度

12

这个问题有很多变种,但我还没有找到正确的答案。

假设我在文件服务器上有一个 .jpg 图像,并且我需要获取其高度和宽度。我该如何在 asp.net 中实现?

我看到了一些答案建议这样做:

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

这种方法本来可以正常工作,但是System.Drawing命名空间中的类不能在ASP.NET服务中使用

那么,在ASP.net中如何获取图像的实际高度和宽度呢?


1
相关问题,但不同的是:https://dev59.com/AXRC5IYBdhLWcg3wKtz2 - jball
1
Image.FromStream(stream, false) 将加载宽度和高度,而无需解析所有图像数据。确保您在处理完图像后及时处理流,就可以避免问题了。警告之所以存在是因为平均程序员懒得正确处理手动内存管理。 - Lilith River
9个回答

6
在aspx页面上添加一个服务端图片控件。
<asp:image ID="img1" runat="server" src="" />

在代码后台中为其添加一个src。

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

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

根据问题中提到的MSDN页面,System.Drawing不应在ASP.net中使用。 - Anthony
2
img1.src无论如何都不起作用。你可能是想说img1.ImageUrl。 - Anthony
这个问题的内容明显是错误的,为什么它会有这么多赞成票? - GreySage

4
你可以使用“位图”类。 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

工作正常。漂亮而简单。 - alikuli

1

希望这能帮到你

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);

0

我在一个列表视图中使用了ImageButton来显示我的图片,但是我需要获取它们的宽度和高度,所以我在这里找到了解决方案:

http://forums.asp.net/t/1262878.aspx?how+to+get+the+image+width+and+height+argh

以下是我的可用代码:

    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);

希望能对你有所帮助


0

我已经将C++代码转换为C#以备将来参考:

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
}

使用方法:

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);
    }
}

0

引入 iTextSharp.text 库

这是创建 PDF 文档时所使用的工具。

         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

那是说 服务,而不是 应用程序。那样就可以了。


ASP工作进程不作为服务运行? - jball
http://dotnet.org.za/eduard/archive/2004/09/23/4226.aspx - jball

-1

导入 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
问题中的代码有什么不同? - Anthony

-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
根据问题中提到的MSDN页面,System.Drawing不应在ASP.net中使用。您的“img”变量就是基于它的。另外,img.PhysicalDimension.Width和问题中使用的img.Width有什么区别? - Anthony

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接