非常基本上我有一个图像已转换为 Base64 字符串。以下代码是如何将其转换为 base64string 以及我如何尝试返回它。这是对 phonegap 插件的修改,所以请原谅某些东西的命名。
package org.apache.cordova;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
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);
}
});
PluginResult imageData = new PluginResult(PluginResult.Status.NO_RESULT);
imageData.setKeepCallback(true);
System.out.println("imageData:==================================================================================>>>>>"+imageData);
return imageData;
}
}
这一行:
System.out.println(mytextstring);
输出 base64 字符串,但是这一行:
System.out.println("imageData:==================================================================================>>>>>"+imageData);
没有。我正在尝试让 imageData 包含 base64string,以便我可以返回它并在某些 Javascript 中使用它。我已经玩了一段时间的代码,但没有成功,我是 Java 新手,所以真的不知道我有多接近。有人可以指导我吗?
编辑我只想返回 Base64String,仅此而已。