目标: - 将asp.net图像控件保存到服务器中的文件夹 使用此代码
File.WriteAllBytes(Server.MapPath(imgPath), imageData);
imageData假设为字节数组。
现在我已经非常了解如何将Asp.net Image Control转换为字节数组,但仍然没有找到任何解决方案。 外面的很多例子都展示了如何从UploadFile Control中保存,而不是从Image Control本身保存。
我发现的唯一最接近的是
public static Byte[] ImageToByteArray(Image img)
{
try
{
MemoryStream mstImage = new MemoryStream();
img.Save(mstImage, System.Drawing.Imaging.ImageFormat.Jpeg);
Byte[] bytImage = mstImage.GetBuffer();
return bytImage;
}
catch (Exception ex)
{
}
}
但是我应该通过的正确参数是什么?我尝试传递Image1.ImageUrl,但它返回错误。
非常感谢任何帮助。
答案 0 :(得分:0)
如果您已有一个类似于此的现有Image
控件:
<form id="form1" runat="server">
<asp:Image ID="ExampleImageControl" runat="server" ImageUrl="~/Images/YourImage.jpg" />
</form>
您可以创建一个接受Image控件的方法,读取字节并按照您之前提到的File.ReadAllBytes()
方法按预期返回它们:
public byte[] ImageControlToByteArray(Image image)
{
try
{
// Attempt to find the Image that the control points to
// and read all of it's bytes
return File.ReadAllBytes(Server.MapPath(image.ImageUrl));
}
catch (Exception ex)
{
// Uh oh, there was a problem reading the file
return new byte[0];
}
}
然后你可以按预期检索字节:
var imagebytes = ImageControlToByteArray(YourImageControl);