我有一些 Java 代码可以截屏并输出一个 png,该代码旨在保存到手机的“图片”图库中。它看起来像这样:
package org.apache.cordova;
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.graphics.Bitmap;
import android.os.Environment;
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
public void run() {
View view = webView.getRootView();
view.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache());
view.setDrawingCacheEnabled(false);
try {
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");
FileOutputStream fos = new FileOutputStream(f);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
that.success(new PluginResult(PluginResult.Status.OK), id);
System.out.println("get here?");
} catch (IOException e) {
that.success(new PluginResult(PluginResult.Status.IO_EXCEPTION, e.getMessage()), id);
System.out.println("and here?");
}
}
});
PluginResult result = new PluginResult(PluginResult.Status.NO_RESULT);
result.setKeepCallback(true);
return result;
}
}
现在出于我正在处理的项目的目的,我不想将 t 保存到画廊,而是输出一个可以操作的 base64 字符串。我是 Java 新手,但是在浏览了一些东西之后,我发现了一个 base64 Java 编码器。但似乎有一个名为 Base64OutputStream 的 android util 方法。
我认为我需要替换的代码是:
FileOutputStream fos = new FileOutputStream(f);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
起初我试过:
Base64OutputStream os = new Base64OutputStream();
但它抛出了错误,然后我一直在玩我发现的其他代码。如:
ByteArrayOutputStream os = new ByteArrayOutputStream();
OutputStream b64 = new Base64.OutputStream(os);
ImageIO.write(bi, "png", b64);
String result = os.toString("UTF-8");
它再次不起作用,而不是为我的项目的一小部分实现 base64 编码库,我想知道是否有人能指出我正确的方向,或者告诉我我是否走在正确的道路上。我是Java新手,但觉得android提供的Base64OutputStream一定是关键。有人有任何指示吗?