Save the image to the database, load the image, and load the database

Source: Internet
Author: User

Save the image to the database, load the image, and load the database

public class BinaryToImageConverter:IValueConverter    {        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)        {            if (value is Binary)            {                byte[] bytes = new byte[(value as Binary).Bytes.Length];                 bytes = (value as Binary).Bytes;                 MemoryStream stream = new MemoryStream(bytes, 0, bytes.Length);                 BitmapImage image = new BitmapImage();                try                {                    image.SetSource(stream);                    return image;                }                catch (Exception ex)                {                    MessageBox.Show(ex.ToString());                }            }            if (value is String)            {                string s = value.ToString();                 return s + 1111;            }            return null;        }         public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)        {            throw new NotImplementedException();        }    }
<Grid x: Name = "LayoutRoot" Background = "White"> <Grid. resources> <silverlightApplication2: BinaryToImageConverter x: Key = "BinaryConventer"> </silverlightApplication2: BinaryToImageConverter> </Grid. resources> <StackPanel> <Button x: Name = "btselectfile" Height = "30" Content = "selected files" Click = "btselectfile_Click"> </Button> <Button x: name = "btshow" Height = "30" Content = "" Click = "btupload_Click"> </Button> <ListBo X: Name = "ListBox" Height = "260" SelectionChanged = "ListBox_SelectionChanged"> <ListBox. itemTemplate> <DataTemplate> <StackPanel Orientation = "Vertical"> <TextBlock Height = "30" Text = "{Binding ProductENname, converter = {StaticResource BinaryConventer} "Width =" 100 "> </TextBlock> <Image x: name = "Image" Height = "100" Width = "100" Source = "{Binding ImageBinary, Converter = {StaticResource BinaryConventer}"> </Ima Ge> <! -- <Image x: name = "Image" Height = "100" Width = "100" Source = "{Binding ProductENname}"> </Image> --> </StackPanel> </DataTemplate> </ listBox. itemTemplate> </ListBox> </StackPanel> </Grid>

How to save images to the SQL Server database

Step 1:
// Obtain the currently selected image this. pictureBox1.Image = Image. fromStream (this. openFileDialog1.OpenFile (); // obtain the path of the current image. string path = openFileDialog1.FileName. toString (); // Add the image with the specified path to the FileStream class. FileStream fs = new FileStream (path, FileMode. open, FileAccess. read); // instantiate the BinaryReader object BinaryReader br = new BinaryReader (fs) through the FileStream object; // use the ReadBytes () of the BinaryReader Class Object () method to convert a FileStream object to a binary array byte [] imgBytesIn = br. readBytes (Convert. toInt32 (fs. length ));

Step 2: // Add the image to the database string SQL = "insert into pic values (@ pic )"; sqlParameter [] param = new SqlParameter [] {new SqlParameter ("@ pic", imgBytesIn)}; DBHelper. getExecuteQuery (SQL, param );

Step 3: // extract the image from the database string SQL = "select * from pic where id = 0"; SqlDataReader reader = DBHelper. getExecuteReader (SQL, null); MemoryStream mss = null; if (reader. read () {byte [] bytes = (byte []) reader ["pic"]; mss = new MemoryStream (bytes );}
This. pictureBox2.Image = Image. FromStream (mss );

The above is a copy, but generally do not need to do so, just save the image path.
This. photo. PostedFile. SaveAs (path + "name. Format ");
Save the path to the database.
If the image format is stored in the database, the database will be burdened when there are many images.

How does java store images in a database?

In general, there is a folder on your server that stores images, and the database stores the path of images on your server. When needed, go to the database to obtain the path. What do you want to do after you get the path.
As for how to obtain the path from the database, this is a simple db operation.
Load driver class:
Class. forName (DBDriver );
Get connection:
Connection conn = DriverManager. getConnection (url, username, password );
Create operation object:
PreparedStatement stmt = con. prepareStatement (SQL );

Perform the following operations:
ResultSet rs = stmt.exe cuteQuery ();

Traversal result:
List list = new ArrayList ();
While (rs. next ()){
// Specific operation, usually with the rs. getString (name) Value
Image img = new Image (); // The Image class corresponds to the Image table in your database
Img. setSrc (rs. getString ("src"); // assume that the image address field in the image table in your database is src.
List. add (img );
}
Remember to close the resource:
Rs. close ();
Stmt. close ();
Con. close ();

You can see that you have obtained the information and do not know how to display it:
You can put the image in a list and traverse the list on the page.
<C: forEach var = "chakan1" items = "list">

<Tr>
<Td>

</Td>
</Tr>
</C: forEach>
This is probably the case.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.