You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ionic中cordova-camera-preview拍照后ng2-img-tools图片缩放问题求助

Fix: ng2-img-tools Format Error When Passing File Paths

Hey there! I can spot the root cause right away — you’re passing a webview-accessible URL (from window.Ionic.WebView.convertFileSrc()) to ng2-img-tools, but this library expects actual File objects, not file paths or URLs. That’s why it’s throwing the format error even though your image is a valid JPG/PNG.

Solution Steps

To resolve this, you need to:

  1. Read the image file from its permanent storage path as raw binary data
  2. Convert that data into a Blob, then wrap it into a File object that ng2-img-tools can process

Modified Code

Here’s how to update your takePhoto() method:

takePhoto() {
 this.cameraPreview.takePicture({quality: .7}).then((path) => {
  let tempPath = path[0].substr(0, path[0].lastIndexOf('/') + 1);
  let tempFileName = path[0].replace(tempPath, "");
  let fullTempPath = 'file://' + tempPath;
  var newFilename = this.createFileName();
  var permLocation = this.file.dataDirectory + newFilename;

  // Copy Image to Perm Directory....
  this.file.copyFile(fullTempPath, tempFileName, this.file.dataDirectory, newFilename).then(success => {
    // Dynamically determine MIME type based on file extension
    const fileExtension = newFilename.split('.').pop().toLowerCase();
    const mimeType = fileExtension === 'png' ? 'image/png' : 'image/jpeg';

    // Read file as raw buffer
    this.file.readAsArrayBuffer(this.file.dataDirectory, newFilename).then(buffer => {
      // Convert buffer to Blob, then to File object
      const imageBlob = new Blob([buffer], { type: mimeType });
      const imageFile = new File([imageBlob], newFilename, { type: mimeType });

      // Now use the File object for resizing
      this.ng2ImgToolsService.resize([imageFile], 640, 640).subscribe(result => {
        // Success: result is a resized File object
        console.info('Resized image:', result);
        // Handle the resized file (e.g., upload, save to storage)
      }, error => {
        console.error('Resize error:', error);
      });
    }).catch(readError => {
      console.error('Failed to read file:', readError);
    });
  }, error => {
    console.error('Failed to copy file:', error);
  });
 }, error => {
  console.error('Camera preview error:', error);
 });
}

Key Explanations

  • readAsArrayBuffer: Fetches the raw binary content of the image from Cordova’s file system
  • Blob: Wraps the raw data into a binary container with the correct image MIME type
  • File: Converts the Blob into the browser-native File object that ng2-img-tools requires for processing

This approach ensures you’re feeding the library exactly what it expects, eliminating the false format error.

内容的提问来源于stack exchange,提问作者Dunny

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:48:01