亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 Cordova 插件寫入 Blob 圖像失敗 [ Android ]

使用 Cordova 插件寫入 Blob 圖像失敗 [ Android ]

蠱毒傳說 2023-07-14 09:48:22
我正在嘗試使用 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 在新窗口中打開時 - 輸出在此處但是寫入圖像文件后,這是結果
查看完整描述

1 回答

?
MMTTMM

TA貢獻1869條經驗 獲得超4個贊

我創建了一個單獨的插件,用于將文件 [本機級別] 保存到 Cordova 中的 Android 和 IOS 設備中。我覺得現有的文件編寫器插件有問題


爪哇


private Boolean saveImage(final CallbackContext callbackContext, final String bs64String) {

    cordova.getThreadPool().execute(new SocialSharingRunnable(callbackContext) {

      public void run() {

        //Directory and File

        try {

          String dirName = webView.getContext().getExternalFilesDir(null) + "/";

          File dir = new File(dirName);

          File file = new File(dirName, cordova.getActivity().getApplicationContext().getString(R.string.filename)+".png");

          Log.d("SaveFile", "Save Image");

          Log.d("SaveFile", "dirName  "+dirName);

          //Avoid overwriting a file

       /*   if (!overwrite && file.exists()) {

              callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, "File already exists!"));

          }*/


          //Decode Base64 back to Binary format

          byte[] decodedBytes = Base64.decode(bs64String.getBytes(), Base64.DEFAULT);


          //Save Binary file to phone

          file.createNewFile();

          FileOutputStream fOut = new FileOutputStream(file);

          fOut.write(decodedBytes);

          fOut.close();

          callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, "Saved successfully!"));

        } catch (FileNotFoundException e) {

          callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "File not Found!"));

        } catch (IOException e) {

          callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, e.getMessage()));

        }

      }

    });

    return true;

  }

IOS


- (void)saveImage:(CDVInvokedUrlCommand*)command {

    CDVPluginResult *pluginResult;

    @try

    {

        NSLog(@"========== saveImage ========");

        NSString* strBase64Img = [command.arguments objectAtIndex:0];

        NSLog(@"strBase64Img %@",strBase64Img);

        NSData *imageData = [Sharing dataFromBase64String:strBase64Img];

        UIImage *image = [UIImage imageWithData:imageData];

        

        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);

        NSLog(@"paths %@",paths);

        NSString *documentsDirectory = [paths objectAtIndex:0];

        NSLog(@"documentsDirectory %@",documentsDirectory);

        NSString *getImagePath = [documentsDirectory stringByAppendingPathComponent:@"ImageName.png"];

        [UIImagePNGRepresentation(image) writeToFile:getImagePath atomically:YES];

        

        NSString *savedImage = @"Successfully saved";

        pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:savedImage];

        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];

    }

    @catch(id anException) {

        NSString *failImg = @"Failed to Save";

        pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:failImg];

        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];

    }

}

腳本語言


   cordova.exec(onSaveSuccess, onSaveError, "Sharing", "saveImage", [base64Canvas]);


查看完整回答
反對 回復 2023-07-14
  • 1 回答
  • 0 關注
  • 190 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號