将文件作为镜像文件写入android中的sd卡

Write file to sd card in android as image file

本文关键字:文件 android 中的 sd 镜像      更新时间:2023-09-26

我想在这里问你一些问题。

我正在使用Phonegap构建一个应用程序,可以拍照,然后在画布上显示图片。在画布中绘制图像后,我使用一种方法将画布转换为图像文件。但我在安卓系统中将文件作为图像文件写入SD卡时遇到了一个问题,即我无法读取在SD卡中创建的图像文件(图像无效)。

这是我的代码:

var picture = "";
function takePhoto() {
    navigator.camera.getPicture(onCameraSuccess,
    onCameraError,{
        quality : 50,
        destinationType : Camera.DestinationType.FILE_URI
        //saveToPhotoAlbum: true
        });
}
function onCameraSuccess(imageURL) {   
   var canvas = document.getElementById('myCanvas');    
   var ctx=canvas.getContext("2d");
   var imageObj = new Image();
   imageObj.onload = function() {
    ctx.drawImage(imageObj, 0, 0,220,180);
  };
  imageObj.src=imageURL;
  picture = imageURL;
}
function onCameraError(e) {
    console.log(e);
    navigator.notification.alert("onCameraError: " + e +" (" + e.code + ")");
}
function storePhoto() {                  
     movePic(pictures); 
}
function movePic(){
    window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
}
function gotFS(fileSystem) {        
    fileSystem.root.getFile("test.PNG", {create: true, exclusive: false}, gotFileEntry, fail);
}
function gotFileEntry(fileEntry) {
    fileEntry.createWriter(gotFileWriter, fail);
}
function gotFileWriter(writer) {    
     var c = document.getElementById('myCanvas');    
     var img_from_canvas=c.toDataURL("image/png"); // base64 encoded
     var pic = img_from_canvas.split("base64,");
     var pictures =window.atob(pic[1]);         // decode base64
     writer.write(pictures);
     alert("Your picture was successfully stored !")
}
function fail(error) {
    console.log(error.code);
}

我很感激你的帮助和建议。

您在用画布捕捉图像后是否对图像进行了任何类型的编辑?如果没有,那么你可以尝试这个代码将文件移动到根文件夹

var fs;
function movePic(){
    window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
}
function gotFS(fileSystem) {        
    fs = fileSystem;
    window.resolveLocalFileSystemURI(picture, gotFileEntry, fail);
}
function gotFileEntry(fileEntry) {
    fileEntry.moveTo( fs.root,fileEntry.name, success, fail);
}
function fail(error) {
    console.log(error.code);
}

您对writer.write(图片)有问题;

试试这个

var buffer = new ArrayBuffer(pictures.length);
var array = new Uint8Array(buffer);
    for (var i = 0; i < pictures.length; i++) {
          array[i] = pictures.charCodeAt(i);
         }
writer.write(buffer);

它对我有用。