You can create a class in a common package as follows, then call createByteArray()
from client-side and convert image into a byte array. Then pass it into a skeleton and reconstruct an image using createBufferedImage()
. Finally, save it as a JPEG using toFile()
:
/**
*
* @author Randula
*/
public class TransportableImage {
/**
*
* @param bufferedImage
* @return
* @throws IOException
*/
public byte[] createByteArray(BufferedImage bufferedImage)
throws IOException {
byte[] imageBytes = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
JPEGImageEncoder jpg = JPEGCodec.createJPEGEncoder(bos);
jpg.encode(bufferedImage);
bos.flush();
imageBytes = bos.toByteArray();
bos.close();
return imageBytes;
}
//Reconstruct the BufferedImage
public BufferedImage createBufferedImage(byte[] imageBytes)
throws IOException {
InputStream is = new ByteArrayInputStream(imageBytes);
JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(is);
BufferedImage image = decoder.decodeAsBufferedImage();
is.close();
return image;
}
//Save a JPEG image
public void toFile(File file, byte[] imageBytes)
throws IOException {
FileOutputStream os = new FileOutputStream(file);
os.write(imageBytes, 0, imageBytes.length);
os.flush();
os.close();
}
}