Depending upon what sort of encryption you had in mind - you can use ImageIO to write/read the image to Output and Input Streams, taking the resulting bytes and decrypt/encrypt.
To save the image, use ImageIO to write the Image to an OutputStream (for example a ByteArrayOutputStream ). From the bytes written, you can encrypt, and then save
ByteArrayOutputStream os = null;
OutputStream fos = null;
try{
os = new ByteArrayOutputStream();
ImageIO.write(image, "jpg", os);
byte[] bytes = os.toByteArray();
encrypt(bytes);
fos = new FileOutputStream(outputfile);
fos.write(bytes);
}catch(IOException e){
e.printStackTrace();
}finally{
if ( fos != null ){try{fos.close();}catch(Exception e){}}
if ( os != null ){try{os.close();}catch(Exception e){}}//no effect, but hear for sanity's sake
}
To read the and decrypt, just read the file as bytes, decrypt the bytes, then send the byte stream to ImageIO
InputStream is = null;
ByteArrayOutputStream os = null;
ByteArrayInputStream input = null;
try{
is = new FileInputStream(inputFile);
os = new ByteArrayOutputStream ();
byte[] buffer = new byte[500];
int len = -1;
while ( ( len = is.read(buffer) ) != -1 ){
os.write(buffer, 0, len);
}
byte[] fileBytes = os.toByteArray();
decrypt(fileBytes);
input = new ByteArrayInputStream(fileBytes);
Image image = ImageIO.read(input);
}catch(IOException io){
io.printStackTrace();
}finally{
if ( is != null ){try{is.close();}catch(Exception e){}}
if ( os != null ){try{os.close();}catch(Exception e){}}
if ( input != null ){try{input.close();}catch(Exception e){}}
}
The type of encryption you use is your choice. You can use a simple Cipher to encrypt the byte array using a bitwise exclusive or (^)
for ( int i = 0; i < bytes.length; i++ ){
bytes[i] = (byte)(bytes[i] ^ 123);
}
Or more fancy encryption using a Cipher
Note that for animated gif's, you may need to search for a way to save the frames of the gif (for instance see this)