-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBmpCodec.java
More file actions
62 lines (52 loc) · 2.18 KB
/
Copy pathBmpCodec.java
File metadata and controls
62 lines (52 loc) · 2.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package me.tamkungz.codecmedia.internal.image.bmp;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import javax.imageio.ImageIO;
import me.tamkungz.codecmedia.CodecMediaException;
public final class BmpCodec {
private BmpCodec() {
}
public static BufferedImage decode(Path input) throws CodecMediaException {
try {
BufferedImage image = ImageIO.read(input.toFile());
if (image == null) {
throw new CodecMediaException("Unable to decode BMP: " + input);
}
validateDecodedImage(image, input);
return image;
} catch (IOException e) {
throw new CodecMediaException("Failed to decode BMP: " + input, e);
}
}
public static BmpProbeInfo probe(Path input) throws CodecMediaException {
try {
byte[] bytes = Files.readAllBytes(input);
return BmpParser.parse(bytes);
} catch (IOException e) {
throw new CodecMediaException("Failed to probe BMP: " + input, e);
}
}
public static void encode(BufferedImage image, Path output) throws CodecMediaException {
try {
boolean written = ImageIO.write(image, "bmp", output.toFile());
if (!written) {
throw new CodecMediaException("No BMP writer available in ImageIO runtime");
}
} catch (IOException e) {
throw new CodecMediaException("Failed to encode BMP: " + output, e);
}
}
private static void validateDecodedImage(BufferedImage image, Path input) throws CodecMediaException {
if (image.getWidth() <= 0 || image.getHeight() <= 0) {
throw new CodecMediaException("Decoded BMP has invalid dimensions: " + input);
}
if (image.getColorModel() == null || image.getColorModel().getPixelSize() <= 0) {
throw new CodecMediaException("Decoded BMP has invalid bit depth: " + input);
}
if (image.getRaster() == null || image.getRaster().getNumBands() <= 0) {
throw new CodecMediaException("Decoded BMP has invalid pixel channels: " + input);
}
}
}