【发布时间】:2013-01-18 11:01:18
【问题描述】:
我想在android中开发一个应用程序,我需要在其中捕获图像并将该图像转换为字符串并将该字符串写入txt文件并将其发送到服务器读取该文件并将该字符串再次转换为图像的服务器。 .
现在我已经完成了图像参与并将该图像转换为字符串并将该字符串写入 txt 文件。
但是当我尝试读取该文件并将该字符串转换为图像时,它不起作用...
图片转字符串的代码是
File imageFile = new File(path);
Bitmap bitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream);
byte[] image = stream.toByteArray();
imgstr = Base64.encodeToString(image, 0);
将其写入文件的代码是
File file = new File("new.txt");
FileWriter w = new FileWriter("/sdcard/new/new.txt");
BufferedWriter out = new BufferedWriter(w);
out.write(data);
out.flush();
out.close();
读取该文件并将该字符串再次转换为图像的代码是
FileInputStream fstream = new FileInputStream("/sdcard/new/new.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
ArrayList list=new ArrayList();
while ((strLine = br.readLine()) != null)
{
list.add(strLine);
}
Iterator itr;
for (itr=list.iterator(); itr.hasNext(); )
{
String str=itr.next().toString();
StringBuffer sb=new StringBuffer(str);
int length=sb.length();
String imageDataString = sb.substring(0, length);
byte[] decodedString = Base64.decode(imageDataString, Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0,decodedString.length);
FileOutputStream imageOutFile = new FileOutputStream("/sdcard/new/android.jpg");
imageOutFile.write(decodedString);
imageOutFile.close();
System.out.println("File converted");
但它没有将该字符串转换为图像 请告诉我解决方案...
【问题讨论】:
-
尝试输出您在
Base64.encode之后获得的字符串,然后将您传递给Base64.decode进行比较。如果它们太长而无法比较 - 输出它们的哈希值并检查它们是否相等。 -
@yograjshinde 究竟为什么要将图像转换为字符串来发送?这是某种自制的密码学吗?字符串的唯一优点是内容/格式操作,但这绝对不是操作图像的方式。为什么不直接上传图片?另外,转换为字符串的图像数据可能会占用更多空间。请满足我的好奇心,因为你肯定有这样做的理由。
-
为什么是图像 -> 字符串 -> 图像?只需将其作为字节数组发送即可。
-
@Nikita Beloglazow 您好,感谢您的回复,我已经检查过它显示它不相等......你有什么建议吗?
-
@YograjShinde 如果这是您遇到的问题,那么其他地方会出现更大的问题。解决最初的问题,而不是绕过它。