我正在为PC制作一个2D游戏,这个游戏有像精灵,音效,音乐和文本这样的数据。
问题是我需要以某种方式储存它。
现在,我需要以加密的格式存储我的精灵,我需要我的Java游戏对加密的图像进行解密,并将加密的图像加载到bufferedimages,以便在我的游戏中显示它们。
我不想将所有内容封装到一个可执行的.jar或.exe文件中。
我需要使我的图像(参考资料,Spritesheets)加密和安全,因为我不想让播放器干扰或使用它们。
我不能使用ZIP文件,甚至不能使用某种Java库加密或保护的文件,因为Java必须先在磁盘上导出它们,然后才能使用它
我已经搜索了许多论坛,我找不到一个明确的答案。
发布于 2015-04-22 21:28:15
取决于您想到的是哪种加密方式--您可以使用ImageIO将图像写入/读取到输出和输入流,获取得到的字节并解密/加密。
若要保存图像,请使用ImageIO将图像写入OutputStream (例如,ByteArrayOutputStream )。从编写的字节中,您可以加密,然后保存
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
}要读取和解密,只需将文件读取为字节,解密字节,然后将字节流发送到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){}}
}您使用的加密类型是您的选择。您可以使用简单密码对字节数组使用位独占或(^)进行加密。
for ( int i = 0; i < bytes.length; i++ ){
bytes[i] = (byte)(bytes[i] ^ 123);
}或者使用密码学进行更复杂的加密
注意,对于动画gif,您可能需要搜索一种保存gif帧的方法(例如,请参见这)
https://stackoverflow.com/questions/29808769
复制相似问题