這裏有相當多的代碼對我來說太袒露了。我有一個我修改過的phonegap插件。 Java部分輸出一個base64字符串:來自Java的Base64字符串損壞
package org.apache.cordova;
import java.io.ByteArrayOutputStream;
import java.io.File;
import org.apache.cordova.api.Plugin;
import org.apache.cordova.api.PluginResult;
import org.json.JSONArray;
import android.annotation.TargetApi;
import android.graphics.Bitmap;
import android.os.Environment;
import android.util.Base64;
import android.view.View;
public class Screenshot extends Plugin {
@Override
public PluginResult execute(String action, JSONArray args, String callbackId) {
// starting on ICS, some WebView methods
// can only be called on UI threads
final Plugin that = this;
final String id = callbackId;
super.cordova.getActivity().runOnUiThread(new Runnable() {
//@Override
@TargetApi(8)
public void run() {
View view = webView.getRootView();
view.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache());
view.setDrawingCacheEnabled(false);
File folder = new File(Environment.getExternalStorageDirectory(), "Pictures");
if (!folder.exists()) {
folder.mkdirs();
}
File f = new File(folder, "screenshot_" + System.currentTimeMillis() + ".png");
System.out.println(folder);
System.out.println("screenshot_" + System.currentTimeMillis() + ".png");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] b = baos.toByteArray();
String base64String = Base64.encodeToString(b, Base64.DEFAULT);
String mytextstring = "data:image/png;base64,"+base64String;
System.out.println(mytextstring);
that.success(new PluginResult(PluginResult.Status.OK, mytextstring), id);
}
});
PluginResult imageData = new PluginResult(PluginResult.Status.NO_RESULT);
imageData.setKeepCallback(true);
System.out.println("imageData=============>>>>>"+imageData);
return imageData;
}
}
然後我把這個傳給一些Javascript,然後把字符串發送到服務器。我檢查了.php文件接收的字符串,並且base64字符串是相同的。但是,當我解碼base64字符串似乎損壞。舉一個更好的例子,將這個文本文件的內容複製到一個解碼器中。
http://dl.dropbox.com/u/91982671/base64.txt
注:當PHP文件嘗試將其解碼的數據:圖像/ PNG; BASE64,是盈,我剛剛刪除它爲了便於您將其粘貼到一個解碼器。
解碼器在這裏找到:
http://www.motobit.com/util/base64-decoder-encoder.asp
所有我能想到的是,由於某種原因,我可能無法正確從Java輸出的base64字符串。有誰知道發生了什麼事?或者可能導致這種情況?
你嘗試解碼並保存之前,你把它發送到JavaScript? 也許你應該嘗試使用Sun Java進行解碼?看看這個鏈接: http://stackoverflow.com/questions/469695/decode-base64-data-in-java –
您是否嘗試過在編碼之前保存png圖像,以查看它是否在壓縮步驟期間或之前被損壞? – gigadot
您是否嘗試過commons-codec Base64編碼器以查看您是否具有相同的結果?儘管它有這個外部需求,但它確實意味着你也可以支持Android 2.1設備。這就是Cordova目前用於Base64編碼的原因。 –