1

Hi everyone i have a problem with my code, i save the image as varbinary ok, but i want the image to show in a picturebox when selected from a fileupload, but i keep on getting a error, is is it possible ? i'm using c# and asp.net. i've been searching but i cant seem get the code working on my source.

using System;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web.UI.WebControls;
using System.IO;
using System.Drawing;

public partial class Mensagem : System.Web.UI.Page
{           
    protected void BtnUploadClick(object sender, EventArgs e)
    {
        string filePath = Server.MapPath(upload1.FileName);
        string filename = Path.GetFileName(filePath);
        string ext = Path.GetExtension(upload1.PostedFile.FileName);
        Stream fs = upload1.PostedFile.InputStream;
        BinaryReader br = new BinaryReader(fs);
        Byte[] bytes = br.ReadBytes((Int32)fs.Length);
         string dt = DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss");    

        SqlConnection conn = new SqlConnection("Data Source=Microsoft SQL Server (SqlClient);Server=NEVETS-LAPTOP\\NEVETS;Initial Catalog=Forum;uid=sa;pwd=sql;Connect Timeout=10;TrustServerCertificate=True ");
                conn.Open();

            SqlCommand sqlCommand = conn.CreateCommand();
            sqlCommand.CommandType = CommandType.StoredProcedure;
            sqlCommand.CommandText = "usp_inserirFicheiro";                
            sqlCommand.Parameters.AddWithValue("@nome", SqlDbType.VarChar).Value = filename;
            sqlCommand.Parameters.AddWithValue("@tamanho", SqlDbType.VarBinary).Value = bytes;
            sqlCommand.Parameters.AddWithValue("@formato", SqlDbType.VarChar).Value = ext;
            sqlCommand.Parameters.AddWithValue("@data", SqlDbType.DateTime).Value = dt;
            sqlCommand.Parameters.AddWithValue("@ficheiro", SqlDbType.VarBinary).Value = br;                            
            sqlCommand.ExecuteNonQuery();
            txtnome.Text = "sucesso";

            conn.Close();

    }


    protected void Button2_Click(object sender, EventArgs e)
    {
        //upload1.SaveAs(Server.MapPath("~/imgs/" + upload1.FileName).ToString());
        //pbficheiro.ImageUrl = @"~/imgs/" + upload1.FileName;


 Byte[] ba = new BinaryReader(upload1.PostedFile.InputStream).ReadBytes((Int32)upload1.PostedFile.InputStream.Length);
using (MemoryStream ms = new MemoryStream(ba, false))
{
    Image imgTmp = Image.FromStream(ms);
    Bitmap bm = new Bitmap(imgTmp.Width, imgTmp.Height);
    Graphics g = Graphics.FromImage(bm);
    g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
    g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
    g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
    Rectangle rect = new Rectangle(0, 0, imgTmp.Width, imgTmp.Height);
    g.DrawImage(imgTmp, rect, 0, 0, imgTmp.Width, imgTmp.Height, GraphicsUnit.Pixel);

    using (MemoryStream ms2 = new MemoryStream())
    {
        bm.Save(ms2, imgTmp.RawFormat);
          bm.Dispose();
          imgTmp.Dispose();
          if (WantAnImage)
              return Image.FromStream(ms2);
          else (WantBytes)
              ms2.ToArray();}
    }
}

}

1 Answers1

0

If the error is memory related, then it's likely because the image data is being disposed with the Stream object when this method exits. Try capturing it into an intermediate Bitmap object and assigning that Bitmap to the PictureBox image property instead.

Here's a link that might help:

Saving Image to MemoryStream- Generic GDI+ Error

Ultimately, this is referenced as an information source:

http://msdn.microsoft.com/en-us/library/z7ha67kw

Edit:

I don't know what type "upload1" is or its scope, but assuming it's a local object, I wonder about this approach (this would be a method you'd call to retrieve the Byte[] or the Image):

protected void Button2_Click(object sender, EventArgs e)
{
    //upload1.SaveAs(Server.MapPath("~/imgs/" + upload1.FileName).ToString());
    //pbficheiro.ImageUrl = @"~/imgs/" + upload1.FileName;

    Byte[] ba = new BinaryReader(upload1.PostedFile.InputStream).ReadBytes((Int32)upload1.PostedFile.InputStream.Length);
    using (MemoryStream ms = new MemoryStream(ba, false))
    {
        System.Drawing.Image imgTmp = System.Drawing.Image.FromStream(ms);
        Bitmap bm = new Bitmap(imgTmp.Width, imgTmp.Height);
        Graphics g = Graphics.FromImage(bm);
        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
        g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
        Rectangle rect = new Rectangle(0, 0, imgTmp.Width, imgTmp.Height);
        g.DrawImage(imgTmp, rect, 0, 0, imgTmp.Width, imgTmp.Height, GraphicsUnit.Pixel);
                bm.Save(Server.MapPath("~/imgs/" + upload1.FileName).ToString());
                pbficheiro.ImageUrl = @"~/imgs/" + upload1.FileName;
    }
}
Community
  • 1
  • 1
DonBoitnott
  • 10,787
  • 6
  • 49
  • 68
  • thanks for the answer, what im trying to do is this protected void Button2_Click(object sender, EventArgs e) { upload1.SaveAs(Server.MapPath("~/imgs/" + upload1.FileName).ToString()); pbficheiro.ImageUrl = @"~/imgs/" + upload1.FileName; but without the need to save the file locally... i hope you understood... – user2427935 May 28 '13 at 13:05
  • That's a bit different from your original posted code, then. But the first go at it wasn't bad, I just fear the memory was lost. And it didn't require a local save (neither does my suggestion). You simply need to hand that memory off to something that isn't to be immediately disposed, such as passing it through a local Bitmap object or some similar construct that does not rely upon the MemoryStream. – DonBoitnott May 28 '13 at 13:10
  • thanks for the fast answer, ive been trying to get it from memory like you said but i dont think im getting it right... i keep on getting errors on my code. Cannot implicity convert type ... any suggestions ? – user2427935 May 28 '13 at 13:19
  • and thats the upload button, i was refering when i click the "browse..." when i click ok it would load directly into the picturebox then if i wanted to save i would click upload... was i clear enough ? thanks for the help – user2427935 May 28 '13 at 13:23
  • thanks for your help im getting a weird error : CS1525: Invalid expression term 'return' – user2427935 May 28 '13 at 14:35
  • If you are using that code in your original method, you'll want to assign those values, not return them. Your method is type Void, and will not allow return statements. If it's a new method, make the return type something appropriate. – DonBoitnott May 28 '13 at 14:38
  • i removed the return from the last line but im still getting errors .. System.Web.UI.WebControls.Image' does not contain a definition for 'FromStream'... – user2427935 May 28 '13 at 14:39
  • You need the System.Drawing namespace. – DonBoitnott May 28 '13 at 14:42
  • i already do, as you can see on the top, ill post my code file. i have a FileUpload button a Picturebox and a button. ill edit my code on top so you can see what could be wrong im getting this now 'Image' is an ambiguous reference between 'System.Web.UI.WebControls.Image' and 'System.Drawing.Image' – user2427935 May 28 '13 at 14:45
  • still getting this 'Image' is an ambiguous reference between 'System.Web.UI.WebControls.Image' and 'System.Drawing.Image , you know why? youve been a great help thanks ;) – user2427935 May 28 '13 at 15:01
  • As it suggests, "Image" alone is not determinate. Therefore, you'll need to replace it with fully qualified name: System.Drawing.Image. (I should have done this, but forgot about your usage of the Web dll) – DonBoitnott May 28 '13 at 15:03
  • thanks i realized after you said it, and just noticed you update the code, but i still cant get it running..... 'System.Web.UI.WebControls.Image' does not contain a definition for 'Image' and no extension method 'Image' accepting a first argument of type 'System.Web.UI.WebControls.Image' could be found (are you missing a using directive or an assembly reference?) – user2427935 May 28 '13 at 15:15
  • I think you will have to save the image and then assign the path. It appears 'System.Web.UI.WebControls.Image is only a container for a URL to an image to be displayed by the browser, and cannot actually hold the image bytes. See latest edit. – DonBoitnott May 28 '13 at 15:24
  • so its the code i had, i have to save the file each time before if i want to see it as a temporary file... thanks alot for your patience – user2427935 May 28 '13 at 15:32