我正在使用此Android Screenshot Library来捕获屏幕截图。我想在网络浏览器中显示这个屏幕截图。
我在PC上编写了一个小插座应用程序,它连接到Android手机并将捕获的屏幕截图编码为base64。
String base64 = Base64.getEncoder().encodeToString(bytes);
这个base64正在通过websocket发送到网页。下面是我的html / JS代码,它应该在画布上绘制图像。我已将base64图像数据存储在文本文件中以供测试。
<div style="background: aqua; width: 500px; height: 660px;">
<canvas style="width: 480px; height: 640px;" id="sim">
</canvas>
</div>
<script type="text/javascript">
var ctx;
var width = 480;
var height = 640;
(function start() {
ctx = document.getElementById("sim").getContext("2d");
loadFromFile();
})();
function loadImage(data) {
var image = new Image();
image.onload = function() {
//this part never executes
ctx.drawImage(image, 0, 0);
console.log("images loaded!");
}
image.src = "data:image/png;base64," + data;
}
function loadFromFile() {
//please get data from **https://app.box.com/s/e19ww51fd37h4sy8getjnag31ud6tpp9**
var file = "imagefile.txt";
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, true);
rawFile.onreadystatechange = function() {
if (rawFile.readyState === 4) {
if (rawFile.status === 200 || rawFile.status == 0) {
var data = rawFile.responseText;
console.log("data loaded: " + data.length);
loadImage(data);
}
}
}
rawFile.send(null);
}
</script>
为方便起见,这里是相同代码的JsFiddle。
请指出正确的算法,如何从原始未压缩数据生成PNG。代码示例会很棒;)
由于
答案 0 :(得分:1)
public static String encodeTobase64(Bitmap image)
{
Bitmap immagex=image;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
immagex.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] b = baos.toByteArray();
String imageEncoded = Base64.encodeToString(b,Base64.DEFAULT);
Log.e("LOOK", imageEncoded);
return imageEncoded;
}
public static Bitmap decodeBase64(String input)
{
byte[] decodedByte = Base64.decode(input, 0);
return BitmapFactory.decodeByteArray(decodedByte, 0, decodedByte.length); }
答案 1 :(得分:0)
1)不是通过style或css设置画布的尺寸,只有这样
<canvas width="480" height="640">
或
canvas //canvas variable
canvas.width = 480;
canvas.height = 640;
2)用画布尺寸绘制图像,这样做
ctx.drawImage(image, 0, 0, image.width,image.height);
或
canvas.width=image.width;
canvas.height=image.height;
ctx.drawImage(image, 0, 0);