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:
- Read the image file from its permanent storage path as raw binary data
- Convert that data into a
Blob, then wrap it into aFileobject thatng2-img-toolscan 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 systemBlob: Wraps the raw data into a binary container with the correct image MIME typeFile: Converts the Blob into the browser-nativeFileobject thatng2-img-toolsrequires for processing
This approach ensures you’re feeding the library exactly what it expects, eliminating the false format error.
内容的提问来源于stack exchange,提问作者Dunny
相关产品推荐
相关产品推荐

