java读取图片文件转为BASE64编码 读了哪些东西?求大佬解答
如下两个小函数:
第一个将文件读到byte数组中,再将byte数组进行base64编码。有个问题就是读取到byte数组里面的仅仅只有文件的内容吗?是否包括文件的属性:文件名 大小等,转为base64编码后除了读文件头还能有其他方式知道文件类型吗(jpg/jpeg/png/bmp)?
第二个是base64解码方法,文件解码后为啥每个字节要加256?感觉加256和不加256没什么变化呀?
public static String GetImageStr(String path)
{
String imgFile = path;
InputStream in = null;
byte[] data = null;
try
{
in = new FileInputStream(imgFile);
data = new byte[in.available()];
in.read(data);
in.close();
}
catch (IOException e)
{
e.printStackTrace();
}
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(data);
}
public static boolean GenerateImage(String imgStr,String photoname)
{
BASE64Decoder decoder = new BASE64Decoder();
try
{
byte[] b = decoder.decodeBuffer(imgStr);
for(int i=0;i<b.length;++i)
{
if(b[i]<0)
{
b[i]+=256;
}
}
String imagePath= Config.getUploadPhysicalPath();
String imgFilePath = imagePath+photoname;
OutputStream out = new FileOutputStream(imgFilePath);
out.write(b);
out.flush();
out.close();
return true;
}
catch (Exception e)
{
return false;
}
}