11package alpine .binary ;
22
3+ import io .netty .buffer .ByteBuf ;
4+
5+ import javax .imageio .ImageIO ;
6+ import java .awt .image .BufferedImage ;
7+ import java .io .ByteArrayInputStream ;
8+ import java .io .ByteArrayOutputStream ;
9+ import java .io .IOException ;
310import java .nio .charset .StandardCharsets ;
411import java .util .UUID ;
512
13+ import static alpine .binary .ArrayBinaryCodecs .BYTE_ARRAY ;
614import static alpine .binary .BinaryCodec .LONG ;
715
816/**
@@ -20,4 +28,29 @@ interface StandardBinaryCodecs {
2028 LONG , java .util .UUID ::getMostSignificantBits ,
2129 LONG , java .util .UUID ::getLeastSignificantBits ,
2230 UUID ::new );
31+
32+ /**
33+ * Returns binary codec which serializes an image.
34+ * @return A binary codec which serializes an image.
35+ * @see java.awt.image.BufferedImage
36+ */
37+ static BinaryCodec <BufferedImage > image (String format ) {
38+ return BYTE_ARRAY .map (
39+ array -> {
40+ try (var stream = new ByteArrayInputStream (array )) {
41+ return ImageIO .read (stream );
42+ } catch (IOException e ) {
43+ throw new RuntimeException ("Failed to read image!" , e );
44+ }
45+ },
46+ image -> {
47+ try {
48+ var stream = new ByteArrayOutputStream ();
49+ ImageIO .write (image , format , stream );
50+ return stream .toByteArray ();
51+ } catch (IOException e ) {
52+ throw new RuntimeException ("Failed to write image!" , e );
53+ }
54+ });
55+ }
2356}
0 commit comments