Load image from a filepath via BufferedImage

前端 未结 5 1118
耶瑟儿~
耶瑟儿~ 2020-12-20 12:01

I have a problem with Java application, particular in loading a image from a location in my computer.

Following this post I used a BufferedImage and a <

5条回答
  •  难免孤独
    2020-12-20 12:50

    //This code snippet read an image from location on the computer and writes it to a different location on the disk
    try {
        byte[] imageInByte;
    
        BufferedImage imageOnDisk = ImageIO.read(new File("C:\\ImageTest\\pic2.jpg"));
    
        //Create a ByteArrayOutputStrea object to write image to
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
    
        //Write the image to the OutputStream
        ImageIO.write(imageOnDisk, "jpg", baos);
    
        baos.flush();
    
        //Initialise the byte array object with the image that was written to the OutputStream
        imageInByte = baos.toByteArray();
        baos.close();
    
        // convert byte array back to BufferedImage
        InputStream in = new ByteArrayInputStream(imageInByte);
        BufferedImage bImageFromConvert = ImageIO.read(in);
    
        //write the image to a new location with a different file name(optionally)
        ImageIO.write(bImageFromConvert, "jpg", new File(
                "c:\\index.jpg"));
    } catch (IOException e) {
        e.printStackTrace();
    }
    

提交回复
热议问题