首页 > 解决方案 > 如何在asp.net c#中返回图像方法的图像字节

问题描述

protected void Register_Click(object sender, EventArgs e)
{
    Properties.username = UN_TextBox.Text;
    Properties.Email = Email_TextBox.Text;
    Properties.Pass = Pass_TextBox.Text;
    Properties.Gender = Gen_RadioButtonList.Text;
    Properties.Img = img();

    int a = UserAccessLogic.Signup();
    if (a > 0)
    {
        Msg_Label.Text = ("Registration successful..!");
    } else {
        Msg_Label.Text = ("Registration fail..!");
    }
}



private byte[] img()
{
    string path = Server.MapPath("Picture/");
    if (FileUpload.HasFile)
    {
        string fname = FileUpload.FileName;
        string extension = Path.GetExtension(fname);

        if (extension.ToLower() == ".jpg" || extension.ToLower() == ".png" || extension.ToLower() == ".jpeg")
        {
            FileUpload.SaveAs(Server.MapPath("Images/" + fname));
            //how to return this line of code to byte[] img() method
        }
    }
}

标签: c#asp.net

解决方案


您可以将 Image 读取为字节数组:

string path=Server.MapPath("Images/" + fname);
byte[] imgdata = System.IO.File.ReadAllBytes(path);
return imgdata;

你也可以使用ImageConverter

ImageConverter ic = new ImageConverter();
    byte[] imgdata = (byte[])ic.ConvertTo(img, typeof(byte[]));
    return imgdata ;

推荐阅读