How to Save and Retrive image?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • nur alam
    New Member
    • Mar 2011
    • 9

    How to Save and Retrive image?

    Code:
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using System.IO;
    using System.Drawing.Imaging;
    
    namespace WindowsFormsApplication1
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
                MemoryStream stream = new MemoryStream();
                pictureBox1.Image.Save(stream, ImageFormat.Jpeg);
                byte[] memImageData = stream.ToArray();
    
            }
    
            private void button2_Click(object sender, EventArgs e)
            {
    OpenFileDialog OpenFileMemPhoto = new OpenFileDialog();
    OpenFileMemPhoto.Title = "Open File";
    OpenFileMemPhoto.Filter = "All files (*.*)|*.*|All files (*.*)|*.*";
    OpenFileMemPhoto.FilterIndex = 2;
    OpenFileMemPhoto.RestoreDirectory = true;
    if (OpenFileMemPhoto.ShowDialog() == DialogResult.OK && OpenFileMemPhoto.FileName != null)
                {
    txt_mem_image_address.Text = OpenFileMemPhoto.FileName;
                    pictureBox1.Load(OpenFileMemPhoto.FileName);
                }
            }
        }
    }


    The error is:

    A generic error occurred in GDI+.


    Please give me solutions if any.......
    Last edited by Meetee; Jul 4 '11, 08:03 AM. Reason: code tags added
  • GaryTexmo
    Recognized Expert Top Contributor
    • Jul 2009
    • 1501

    #2
    Can you please be a little more descriptive about where the problem occurs? Does it happen in button1's click event handler, or button2's?

    I've seen this error before (though under slightly different circumstances) and I know the exception gets thrown at the application level. When I saw it the cause was closing a memory stream that I had loaded an image from. This case looks somewhat different but lets be sure of what's going on before I try to start helping you out :)

    Comment

    • nur alam
      New Member
      • Mar 2011
      • 9

      #3
      I have used the following line and problem solved.

      pictureBox1.Ima ge = new Bitmap(OpenFile MemPhoto.FileNa me);


      thank you for your reply

      Comment

      • GaryTexmo
        Recognized Expert Top Contributor
        • Jul 2009
        • 1501

        #4
        Keep in mind that when you do that, an open file handle is left on the file... this isn't always undesirable, just something to be aware of.

        (Loading an image into a memory stream to make a copy is a way to work around this, which is what I thought you were doing :D)

        Comment

        Working...