Bael 7839 (#16426)
* BAEL-7765: How to fix JsonParseException: Unexpected character (code 115) when parsing unquoted JSON in Jackson * BAEL-7839: Converting Image to BufferedImage in Java * BAEL-7839: Converting Image to BufferedImage in Java
This commit is contained in:
parent
7a5cbf3971
commit
c571579a55
@ -1,10 +1,7 @@
|
||||
package com.baeldung.imageprocessing.imagetobufferedimage;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
import java.awt.*;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
|
||||
public class ImageToBufferedImage {
|
||||
|
||||
@ -25,17 +22,7 @@ public class ImageToBufferedImage {
|
||||
if (image instanceof BufferedImage) {
|
||||
return (BufferedImage) image;
|
||||
} else {
|
||||
throw new ClassCastException("Image type is not compatible with BufferedImage");
|
||||
}
|
||||
}
|
||||
|
||||
// Method 3: Using ImageIO Class
|
||||
public BufferedImage convertUsingImageIO(String filePath) throws IOException {
|
||||
try {
|
||||
File file = new File(filePath);
|
||||
return ImageIO.read(file);
|
||||
} catch (Exception e) {
|
||||
throw new IOException("Error reading image file: " + e.getMessage());
|
||||
throw new ClassCastException("Image type is not compatible with BufferedImage.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -50,20 +50,5 @@ public class ImageToBufferedImageIntegrationTest {
|
||||
Image image = new ImageIcon("src/main/resources/images/baeldung.png").getImage();
|
||||
converter.convertUsingCasting(image);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenConvertUsingImageIOWithValidFile_thenImageGeneratedWithoutError() throws IOException {
|
||||
ImageToBufferedImage converter = new ImageToBufferedImage();
|
||||
BufferedImage bufferedImage = converter.convertUsingImageIO("src/main/resources/images/sampleImage.jpg");
|
||||
assertNotNull(bufferedImage);
|
||||
assertEquals(image.getWidth(null), bufferedImage.getWidth());
|
||||
assertEquals(image.getHeight(null), bufferedImage.getHeight());
|
||||
}
|
||||
|
||||
@Test(expected = IOException.class)
|
||||
public void whenConvertUsingImageIOWithInvalidFile_thenImageGeneratedWithError() throws IOException {
|
||||
ImageToBufferedImage converter = new ImageToBufferedImage();
|
||||
converter.convertUsingImageIO("invalid_file.jpg");
|
||||
}
|
||||
}
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user