title: Image to ByteArray to BLOB and BLOB to ByteArray to Image Conversion Issues in Java
body: <p>After a lot of learning on ByteArrays &amp; BLOBS, I managed to write the below Java code to write an image into Access DB (Using ucanaccess) and writing it back to Disk.</p>
  
  <p>When I write an image back to disk the image is in incorrect format or something is messed up that you cannot open that image.</p>
  
  <p>I understand it is not a good practice to store Images on DB but, this is only for my learning.</p>
  
  <pre><code>public static void Update_to_DB() throws SQLException, IOException {
      String URL = "jdbc:ucanaccess://C:\\Users\\bharat.nanwani\\Desktop\\Images.accdb";
      Connection conn = DriverManager.getConnection(URL);
      //Statement stmt = conn.createStatement();
      PreparedStatement p;
  
      File ImgPath = new File("C:\\Users\\bharat.nanwani\\Desktop\\Desert.jpg");
      BufferedImage bufferedimage = ImageIO.read(ImgPath);
  
      WritableRaster raster = bufferedimage.getRaster();
      DataBufferByte data = (DataBufferByte) raster.getDataBuffer();
  
      byte[] bytearray = date.getdata();
  
  
      String query = "INSERT INTO Images(data) VALUES(?);";
      p = conn.prepareStatement(query);
      p.setBinaryStream(1, new ByteArrayInputStream(bytearray),bytearray.length);
      p.execute();
  }
  
  public static void update_to_DISK() throws SQLException, IOException {
          String URL = "jdbc:ucanaccess://C:\\Users\\bharat.nanwani\\Desktop\\Images.accdb";
          Connection conn = DriverManager.getConnection(URL);
          PreparedStatement p;
          ResultSet rs;
          String query = "SELECT Data FROM Images";
                  p=conn.prepareStatement(query);
          rs = p.executeQuery();
          if (rs.next()) {
          Blob blob = rs.getBlob("Data");
  
          byte[] bytearray = blob.getBytes(1L, (int)blob.length());
  
          FileOutputStream fos = new FileOutputStream("C:\\Users\\bharat.nanwani\\Desktop\\New Folder\\test.jpg");
          fos.write(bytearray);
          fos.close();
  
          System.out.println(bytearray);
          } 
      }
  </code></pre>