Android 图像到Base64的转换问题
我正在创建用于图像到base64转换的演示应用程序。一些图像正确转换base64。当映像大小为3.92Mb(4128*3096)并转换为base64时,已成功创建并上载到服务器,但未上载。 Base64后,字符串写入文件,文本文件大小为5.40Mb 下面是图像转换到base64的代码Android 图像到Base64的转换问题,android,Android,我正在创建用于图像到base64转换的演示应用程序。一些图像正确转换base64。当映像大小为3.92Mb(4128*3096)并转换为base64时,已成功创建并上载到服务器,但未上载。 Base64后,字符串写入文件,文本文件大小为5.40Mb 下面是图像转换到base64的代码 public String convertImage(File file) { FileInputStream inputSteam = new FileInputStream(file); i
public String convertImage(File file) {
FileInputStream inputSteam = new FileInputStream(file);
inputSteam.read(getBytesFromFile(file));
return Base64.encodeToString(getBytesFromFile(file, Base64.DEFAULT);
}
public byte[] getBytesFromFile(File file) throws IOException {
InputStream is = new FileInputStream(file);
// Get the size of the file
long length = file.length();
// You cannot create an array using a long type.
// It needs to be an int type.
// Before converting to an int type, check
// to ensure that file is not larger than Integer.MAX_VALUE.
if (length > Integer.MAX_VALUE) {
// File is too large
}
// Create the byte array to hold the data
byte[] bytes = new byte[(int) length];
// Read in the bytes
int offset = 0;
int numRead = 0;
while (offset < bytes.length && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
offset += numRead;
}
// Ensure all the bytes have been read in
if (offset < bytes.length) {
throw new IOException("Could not completely read file "+ file.getName());
}
// Close the input stream and return bytes
is.close();
return bytes;
}
公共字符串转换图像(文件){
FileInputStream inputSteam=新的FileInputStream(文件);
inputSteam.read(getBytesFromFile(file));
返回Base64.encodeToString(getBytesFromFile(文件,Base64.DEFAULT);
}
公共字节[]getBytesFromFile(文件文件)引发IOException{
InputStream is=新文件InputStream(文件);
//获取文件的大小
long length=file.length();
//不能使用长类型创建数组。
//它必须是int类型。
//在转换为int类型之前,请检查
//以确保文件不大于Integer.MAX_值。
if(长度>整数最大值){
//文件太大
}
//创建字节数组以保存数据
字节[]字节=新字节[(int)长度];
//读入字节
整数偏移=0;
int numRead=0;
而(偏移量=0){
偏移量+=numRead;
}
//确保已读入所有字节
if(偏移量<字节长度){
抛出新IOException(“无法完全读取文件”+file.getName());
}
//关闭输入流并返回字节
is.close();
返回字节;
}
如何处理此问题。或任何其他转换图像的方法;如果您使用PHP作为服务器,是否检查了PHP.ini中上载文件的最大大小base64字符串文件应大于原始文件大小,因为base64编码在字符串中添加了自己的字符以保持base64格式。因此,这可能是较大文件大小的问题en原始尺寸。任何其他处理图像的解决方案请查看此链接,它可能会对您有所帮助。