Image in Blob umwandeln

Serethos

Erfahrenes Mitglied
Hallo

gibt es eine möglichkeit ein image in ein Blob umzuwandeln damit ich dann das ganze in eine Mysql DB speichern kann?

danke schön
 
Hallo!

Versuchs mal damit:
Code:
/*
 * Created on 02.11.2004
 */
package de.tutorials;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

/**
 * @author Darimont 
 * mysql> use test; 
 * Database changed 
 * mysql> CREATE TABLE imgStore (ID int, DATA blob); 
 * Query OK, 0 rows affected (0.11 sec)
 *  
 */
public class Test41 {

    private MysqlDataSource mds;

    public Test41() {
        try {
            Thread.currentThread().getContextClassLoader().loadClass(
                    "com.mysql.jdbc.Driver").newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        mds = new MysqlDataSource();
        mds.setDatabaseName("test");
        mds.setUser("root");
        mds.setPassword("");
        mds.setServerName("localhost");
        mds.setPort(3306);

    }

    public static void main(String[] args) {
        new Test41().doIt();
    }

    private void doIt() {
        saveImgInDB();
        loadImgFromDB();
    }

    private void loadImgFromDB() {
        try {
            Connection con = mds.getConnection();

            Statement stmt = con.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT * FROM imgStore");
            if (!rs.next()) {
                return;
            }
            InputStream is = rs.getBinaryStream(2);
            FileOutputStream fos = new FileOutputStream("c:/imgFromDb.jpg");

            byte[] buffer = new byte[2048];
            int len = 0;
            while ((len = is.read(buffer)) > 0) {
                fos.write(buffer, 0, len);
            }
            fos.flush();
            fos.close();
            is.close();
            stmt.close();
            rs.close();
            con.close();

        } catch (SQLException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private void saveImgInDB() {

        try {
            File file = new File("c:/energy.jpg");
            InputStream is = new FileInputStream(file);

            Connection con = mds.getConnection();
            PreparedStatement ps = con
                    .prepareStatement("INSERT INTO imgStore(ID,DATA) VALUES (?,?)");
            ps.setInt(1, 1);
            ps.setBinaryStream(2, is, (int) file.length());

            System.out.println("Updated " + ps.executeUpdate() + " rows!");

            ps.close();
            is.close();

            con.close();
        } catch (SQLException e1) {
            e1.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

Gruß Tom
 
...oder so:
Code:
/*
 * Created on 02.11.2004
 */
package de.tutorials;

import java.awt.BorderLayout;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;

import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

/**
 * @author Darimont 
 * mysql> use test; Database changed 
 * mysql> CREATE TABLE
 *         imgStore (ID int, DATA blob); 
 * Query OK, 0 rows affected (0.11 sec)
 *  
 */
public class Test41 {

    private MysqlDataSource mds;

    public Test41() {
        try {
            Thread.currentThread().getContextClassLoader().loadClass(
                    "com.mysql.jdbc.Driver").newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        mds = new MysqlDataSource();
        mds.setDatabaseName("test");
        mds.setUser("root");
        mds.setPassword("");
        mds.setServerName("localhost");
        mds.setPort(3306);

    }

    public static void main(String[] args) {
        new Test41().doIt();
    }

    private void doIt() {
        saveImgInDB();
        loadImgFromDB();
    }

    private void loadImgFromDB() {
        try {
            Connection con = mds.getConnection();

            Statement stmt = con.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT * FROM imgStore");
            if (!rs.next()) {
                return;
            }
            byte[] bytes = rs.getBytes(2);

            BufferedImage img = ImageIO.read(new ByteArrayInputStream(bytes));
            System.out.println(img);
            JFrame frm = new JFrame();
            frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frm.getContentPane().add(new JLabel(new ImageIcon(img)),
                    BorderLayout.CENTER);
            frm.pack();
            frm.setVisible(true);

            stmt.close();
            rs.close();
            con.close();

        } catch (SQLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private void saveImgInDB() {

        try {
            File file = new File("c:/energy.jpg");

            BufferedImage img = ImageIO.read(file);

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(img, "jpeg", baos);
            baos.flush();

            Connection con = mds.getConnection();
            PreparedStatement ps = con
                    .prepareStatement("INSERT INTO imgStore(ID,DATA) VALUES (?,?)");
            ps.setInt(1, 1);
            ps.setBytes(2, baos.toByteArray());

            System.out.println("Updated " + ps.executeUpdate() + " rows!");

            ps.close();
            baos.close();

            con.close();
        } catch (SQLException e1) {
            e1.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Gruß Tom
 
irgendwie versteh ich PreparedStatement ps = con
.prepareStatement("INSERT INTO imgStore(ID,DATA) VALUES (?,?)");
nicht müsste doch bei values sowas wie die Variablen rein wie ID=1 und Data= mein bild als blob aber wie geht das wenn ich später mit ps.setInt(1, 1);
ps.setBinaryStream(2, is, (int) file.length()); darauf zugreife versteh das kannse irgendwie nicht
 
Hallo!

Da ein PreparedStatement eben nicht direkt auf die Datenbank losgelassen wird und die "?" in dem SQL Statement als Platzhalter dienen kann man dort nachträglich nach belieben die Parameterwerte setzen. Die Nummerierung der Parameter beginnt dabei bei 1 (erstes ? ...)

Gruß Tom
 
ach das ist ja interesant. das wüßte ich bis jetzt garnicht schön das man immer was neues lernt.

danke

hab da aber noch ne frage

kann man den auch das was man ausliest dierect im programm in eine Image Variable schreiben und nicht erst eine Datei anlegen
 
Zurück