-1

I need to read a image in java ad convert to byte array for postgreSQL. I have tried the following code, is it ok?

import java.nio.file.Files;
import java.nio.file.Path;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.Arrays;

public class ConvertImage {

    public static void main(String[] args) throws IOException {

        Path filepath = Paths.get("image.jpg");

        byte[] byteContent = Files.readAllBytes(filepath);

        System.out.println(Arrays.toString(byteContent));
    }
}

And how to do the way back, form byte array to image?

  • Does this answer your question? [File to byte\[\] in Java](https://stackoverflow.com/questions/858980/file-to-byte-in-java) – Mayank Tripathi Apr 26 '20 at 14:13
  • @MayankTripathi no, I have to go from byte array to image –  Apr 26 '20 at 14:20
  • https://stackoverflow.com/questions/6795023/java-load-image-from-file-edit-and-add-to-jpanel – TrogDor Apr 26 '20 at 14:33
  • @TrogDor still different question, I need to convert the variable```byteContent``` into an image from here, and i.e. save it. –  Apr 26 '20 at 14:47

1 Answers1

1

You can create a ByteArrayInputStream from the byte array and supply it to ImageIO as follows:

    ByteArrayInputStream is = new ByteArrayInputStream( byteContent );
    BufferedImage image = ImageIO.read( is );
TrogDor
  • 984
  • 6
  • 14