使用 Cordova 插件写入 Blob 图像失败 [ Android ]

我正在尝试使用 HTML2Canvas 和 CordovaExternalDirectory 将 Base64 图像写入设备存储中。


图像文件已创建,但已损坏。当我使用 BlobUrl 函数打开 blob 图像时,它在新窗口中工作正常。


注意:Android Manifest 中添加了所需的权限


下面的示例代码


var blobUrl;

    function customB64toBlob(b64Data) {

        console.log(" ----- b64Data ----");

        var parts = b64Data.split(";");

        var contentType = parts[0].split(":")[1];

        var realData = parts[1].split(",")[1];

        console.log(parts);

        console.log("Real data");

        contentType = contentType || '';

        sliceSize = 512;

        var byteCharacters = atob(realData);

        var byteArrays = [];


        for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {

            var slice = byteCharacters.slice(offset, offset + sliceSize);


            var byteNumbers = new Array(slice.length);

            for (var i = 0; i < slice.length; i++) {

                byteNumbers[i] = slice.charCodeAt(i);

            }


            var byteArray = new Uint8Array(byteNumbers);


            byteArrays.push(byteArray);

        }


      var blob = new Blob(byteArrays, {type: contentType});

      blobUrl = URL.createObjectURL(blob);

      console.log(blob);

      return blob;

}


function savebase64AsImageFile(folderpath,filename,content){

    // Convert the base64 string in a Blob

    var dataBlob = customB64toBlob(content);

    console.log(" ----- Writing file ----");

    window.resolveLocalFileSystemURL(folderpath, function(dir) {

        console.log("Access to the directory granted succesfully");

        dir.getFile(filename, {create:true}, function(file) {

            console.log("File created succesfully.");

            file.createWriter(function(fileWriter) {

                console.log("Writing content to file");

                fileWriter.write(dataBlob);

            }, function(){

                alert('Unable to save file in path '+ folderpath);

            });

        });

    });

}

当我使用 Bloburl 在新窗口中打开时 - 输出在此处

http://img4.mukewang.com/64b0a9c80001cd2406331291.jpg

但是写入图像文件后,这是结果

http://img1.mukewang.com/64b0a9df0001317e06231290.jpg


蛊毒传说
浏览 162回答 1
1回答

MMTTMM

我创建了一个单独的插件,用于将文件 [本机级别] 保存到 Cordova 中的 Android 和 IOS 设备中。我觉得现有的文件编写器插件有问题爪哇private Boolean saveImage(final CallbackContext callbackContext, final String bs64String) {&nbsp; &nbsp; cordova.getThreadPool().execute(new SocialSharingRunnable(callbackContext) {&nbsp; &nbsp; &nbsp; public void run() {&nbsp; &nbsp; &nbsp; &nbsp; //Directory and File&nbsp; &nbsp; &nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; String dirName = webView.getContext().getExternalFilesDir(null) + "/";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; File dir = new File(dirName);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; File file = new File(dirName, cordova.getActivity().getApplicationContext().getString(R.string.filename)+".png");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Log.d("SaveFile", "Save Image");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Log.d("SaveFile", "dirName&nbsp; "+dirName);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //Avoid overwriting a file&nbsp; &nbsp; &nbsp; &nbsp;/*&nbsp; &nbsp;if (!overwrite && file.exists()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, "File already exists!"));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }*/&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //Decode Base64 back to Binary format&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; byte[] decodedBytes = Base64.decode(bs64String.getBytes(), Base64.DEFAULT);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //Save Binary file to phone&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; file.createNewFile();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; FileOutputStream fOut = new FileOutputStream(file);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fOut.write(decodedBytes);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fOut.close();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, "Saved successfully!"));&nbsp; &nbsp; &nbsp; &nbsp; } catch (FileNotFoundException e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "File not Found!"));&nbsp; &nbsp; &nbsp; &nbsp; } catch (IOException e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, e.getMessage()));&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; });&nbsp; &nbsp; return true;&nbsp; }IOS- (void)saveImage:(CDVInvokedUrlCommand*)command {&nbsp; &nbsp; CDVPluginResult *pluginResult;&nbsp; &nbsp; @try&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; NSLog(@"========== saveImage ========");&nbsp; &nbsp; &nbsp; &nbsp; NSString* strBase64Img = [command.arguments objectAtIndex:0];&nbsp; &nbsp; &nbsp; &nbsp; NSLog(@"strBase64Img %@",strBase64Img);&nbsp; &nbsp; &nbsp; &nbsp; NSData *imageData = [Sharing dataFromBase64String:strBase64Img];&nbsp; &nbsp; &nbsp; &nbsp; UIImage *image = [UIImage imageWithData:imageData];&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);&nbsp; &nbsp; &nbsp; &nbsp; NSLog(@"paths %@",paths);&nbsp; &nbsp; &nbsp; &nbsp; NSString *documentsDirectory = [paths objectAtIndex:0];&nbsp; &nbsp; &nbsp; &nbsp; NSLog(@"documentsDirectory %@",documentsDirectory);&nbsp; &nbsp; &nbsp; &nbsp; NSString *getImagePath = [documentsDirectory stringByAppendingPathComponent:@"ImageName.png"];&nbsp; &nbsp; &nbsp; &nbsp; [UIImagePNGRepresentation(image) writeToFile:getImagePath atomically:YES];&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; NSString *savedImage = @"Successfully saved";&nbsp; &nbsp; &nbsp; &nbsp; pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:savedImage];&nbsp; &nbsp; &nbsp; &nbsp; [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];&nbsp; &nbsp; }&nbsp; &nbsp; @catch(id anException) {&nbsp; &nbsp; &nbsp; &nbsp; NSString *failImg = @"Failed to Save";&nbsp; &nbsp; &nbsp; &nbsp; pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:failImg];&nbsp; &nbsp; &nbsp; &nbsp; [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];&nbsp; &nbsp; }}脚本语言&nbsp; &nbsp;cordova.exec(onSaveSuccess, onSaveError, "Sharing", "saveImage", [base64Canvas]);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript