【问题标题】:Convert Cordova Image Picker Results To Base64 Format Ionic将 Cordova 图像选择器结果转换为 Base64 格式 Ionic
【发布时间】:2018-07-30 09:26:39
【问题描述】:

问题:我试图将图像选择器结果转换为 base64 格式,因为它给出了图像 uri 的结果,并且不想像要求那样使用相机插件从图库中选择多张图片

大多数问题都与此相关问题有关,但对我没有任何帮助,这是我已经解决的问题 Link 1Link 2

这是我尝试将图像转换为 base64 的内容

getImageFromGallery() {

    let options = {
        maximumImagesCount: 3,
        width: 800,
        height: 800,
        quality: 50,
        outputType: 0//image uri 
    };

    this.imagepicker.getPictures(options).then((results) => {

        for (var i = 0; i < results.length; i++) {
            this.imageurlfrompicker = results[i];

            let resizeoptions = {
                uri: results[i],
                quality: 50,
                width: 800,
                height: 800
            } as ImageResizerOptions;
            this.imageResizer
                .resize(resizeoptions)
                .then((filePath: string) => {

                    this.imageurlfromresizer = filePath;

                    this.convertToBase64(filePath, 'image/png').then(
                        data => {
                            this.imagebase64 = data.toString(); //base64 of image
                            console.log(data.toString());
                            //this.base64Image = "data:image/jpeg;base64," + imageData; // old one
                            this.imagelist.push(this.imagebase64);
                            this.imagelist.reverse();


                        }
                    );
                })
                .catch(e => console.log(e));
        }
    }, (err) => { });
}

转成base64的代码

convertToBase64(url, outputFormat) {
    return new Promise((resolve, reject) => {
        let img = new Image();
        img.crossOrigin = 'Anonymous';
        img.onload = function () {
            let canvas = <HTMLCanvasElement>document.createElement('CANVAS'),
                ctx = canvas.getContext('2d'),
                dataURL;
            canvas.height = img.height;
            canvas.width = img.width;
            ctx.drawImage(img, 0, 0);
            dataURL = canvas.toDataURL(outputFormat);
            canvas = null;
            resolve(dataURL);
        };
        img.src = url;
    });
}

请帮忙解决这个问题

Official Link Of Ionic Image Picker

【问题讨论】:

  • 为什么不使用 outputType:1 ?
  • 嗨@SurajRao,我已经尝试使用输出 1,但它不适用于图像选择器,因为 ionic 官方文档没有提到这个问题
  • 表示插件为 outputType 1 提供数据 uri。github.com/Telerik-Verified-Plugins/ImagePicker#options
  • 是的,我已经尝试通过设置 outputType 1 但什么也没返回,这就是我发布这个问题的原因
  • 我觉得这个插件对你有帮助ionicframework.com/docs/native/base64

标签: ionic-framework ionic2 ionic3 cordova-plugins


【解决方案1】:

您可以使用 HTML 5 canvas API,希望这次它对您有所帮助

  function encodeImageUri(imageUri)
{
  var c=document.createElement('canvas');
   var ctx=c.getContext("2d");
   var img=new Image();
    img.onload = function(){
     c.width=this.width;
     c.height=this.height;
     ctx.drawImage(img, 0,0);
    };
   img.src=imageUri;
    var dataURL = c.toDataURL("image/jpeg");
    return dataURL;
}

【讨论】:

    【解决方案2】:

    这个插件肯定会帮到https://ionicframework.com/docs/native/base64/

    我在我的项目中使用它来将图像选择器(画廊和相机)中的数据转换为 base64 字符串。 IT 将 URI 用于参数并使用 base64 返回承诺。我的应用中有类似的示例:

    saveUserImageFromGallery(): any {
                return this.imagePicker.getPictures(this.imagePickerOptions)
                    .then((results) => {
                        return this.resizeAndSave(results[0]);
                    }, () => {
                        console.log('Error picking image');
                    });
        }
    

    使用 Base64 插件

        resizeAndSave(imageUri) {
                return this.cropService.crop(imageUri).then((croppedUri) => {
                        return this.imageResizer
                            .resize({
                                folderName: 'image',
                                uri: croppedUri,
                                quality: 75,
                                width: 300,
                                height: 300,
                                fileName: Date.now() + '.jpg'
                            })
                            .then((filePath: string) => {
                                return this.base64.encodeFile(filePath)
                                    .then(base64File => {
                                        console.log('here is base64 string: ', base64File)
                                        return base64File;
                                    })
                            })
                            .catch(() => {
                                console.log('Error resizing image');
                            });
                    },
                    () => {
                         console.log('Error cropping image');
                    })
            }
    

    使用文件插件

    resizeAndSave(imageUri) {
          return this.cropService.crop(imageUri).then((croppedUri) => {
                return this.imageResizer
                    .resize({
                        folderName: 'image',
                        uri: croppedUri,
                        quality: 75,
                        width: 300,
                        height: 300,
                        fileName: Date.now() + '.jpg'
                    })
                    .then((filePath: string) => {
                        let fileName = filePath.split('/').pop();
                        let path = filePath.substring(0, filePath.lastIndexOf("/") + 1);
                        return this.file.readAsDataURL(path, fileName)
                            .then(base64File => {
                                this.sendUserImage(base64File).subscribe(() => {
                                        console.log("Image saved");
                                    },
                                    (err) => {
                                        console.log('Error saving image');
                                    });
                                return base64File;
                            })
                            .catch(() => {
                                console.log('Error reading file from');
                            })
                    })
                    .catch(() => {
                        console.log('Error resizing image');
                    });
            },
            () => {
                console.log('Error cropping image');
            })
    }
    

    【讨论】:

    • 您的代码在与 ImageResizer 一起使用时工作正常,但我希望用户从图库中选择多个图像并且不想向用户显示图像调整器。你有什么想法吗
    • 本教程应该对您有所帮助:ionicthemes.com/tutorials/about/ionic-2-image-handling 只需更改 reduceImages() 函数并调整图像大小 (ionicframework.com/docs/native/image-resizer),无需用户裁剪。我希望这会有所帮助。
    • 嗨@SurajBahadur 我检查了这个Base64 Ionic Native 插件,它突然停止工作(它仍然是测试版)。我对代码进行了一些更改,并改用了 File Plugin。看看我上面更新的代码。
    • 嗨@Sebastian,谢谢,我使用了ionicthemes.com/tutorials/about/ionic-2-image-handling 的引用,它正在工作并更新您的多张图片代码,以便我可以接受您的回答。
    • 嗨@Sebastian,您对选择多张图片而不向用户显示裁剪有任何想法吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-09
    • 2014-02-15
    • 1970-01-01
    相关资源
    最近更新 更多