java+Mysql保存图片和读取

//数据库的新建

CREATE TABLE photo (
    id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100) COMMENT '名称',
    photo blob COMMENT '照片'
)
ENGINE=InnoDB
DEFAULT CHARSET=utf8
COLLATE=utf8_general_ci;

//从本地文件读取图像的二进制流 

public static FileInputStream getImageByte(String infile) {
        FileInputStream imageByte = null;
        file = new File(infile);
        try {
            imageByte = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return imageByte;

    }


/**
     * 将图片流读出为图片
     * 
     * @param inputStream
     * @param path

     */



  public static void readBlob(InputStream inputStream, String path) {
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(path);
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(buffer)) != -1) {
                fileOutputStream.write(buffer, 0, len);
            }
            inputStream.close();
            fileOutputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

//java 插入数据

 String sql = "insert into photo(id,name,photo) values(?,?,?)";
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setInt(1, 1);
            preparedStatement.setString(2, "李四");
            preparedStatement.setBinaryStream(3, inputStream,
                    inputStream.available());

            preparedStatement.execute();


//读取数据

            String sql = "select p.photo from photo p where id = 1";
            resultSet = statement.executeQuery(sql);
            resultSet.next();
            inputStream = resultSet.getBinaryStream("photo");
            ImageUtil.readBlob(inputStream, "D:\\login.jpg");

你可能感兴趣的:(java+Mysql保存图片和读取)