使用cordova图像缩放器输出需要Base64格式

时间:2017-05-22 10:13:48

标签: cordova ionic2 image-resizing

我正在使用离子2,我需要调整图像大小。因为我使用了这个插件

离子cordova插件添加https://github.com/protonet/cordova-plugin-image-resizer.git

 npm install --save @ionic-native/image-resizer

这是我的代码。

import { NavController, AlertController } from 'ionic-angular';
import { ImagePicker } from '@ionic-native/image-picker';
import { Camera } from 'ionic-native';
import { ImageResizer, ImageResizerOptions } from '@ionic-native/image-resizer';
declare var window: any;

constructor(public alertCtrl: AlertController,private imageResizer: ImageResizer,public platform: Platform,private imagePicker: ImagePicker) {
}

    Choosephoto()
  {
    const options  =   {
        maximumImagesCount: 3, // Android only since plugin version 2.1.1, default no limit
        quality: 90, // 0-100, default 100 which is highest quality
        width: 400,  // proportionally rescale image to this width, default no rescale
        height: 400, // same for height
         destinationType: Camera.DestinationType.DATA_URL,
         sourceType: Camera.PictureSourceType.PHOTOLIBRARY,
         encodingType: Camera.EncodingType.JPEG,      
         correctOrientation: true,
         outputType: 1 // default .FILE_URI
    }
    this.imagePicker.getPictures(options).then((results) => {
      var arr = [];

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

          this.base64Image = "data:image/jpeg;base64," + results[i];
          //console.log("Image URL",this.base64Image);

          if(this.images.length == 0)
          {
              arr.push({
              file:this.base64Image
            })
            this.images=arr;
          }
          else if(this.images.length != 0)
          {
              this.images.push({
              "file":this.base64Image
            })
          }

          let options1 = {
           uri: this.base64Image,
           quality: 90,
           width: 100,
           height: 100,
           outputType:""  
          } as ImageResizerOptions;


          this.imageResizer
            .resize(options1)
            .then((filePath: any) => {
              var image=new Image();
              image.src=filePath;
              var path=image.src;
              console.log("called function");
              this.convertToDataURLviaCanvas(filePath, 'image/png').then(
                data => {
                  console.log(data);
                  let alert = this.alertCtrl.create({
                    title: data.toString(),
                    buttons: ['Dismiss']
                  });
                  alert.present();
                }
              );
              console.log('FilePath', filePath)

             })
            .catch(e => console.log("Failedresizeerr",e));

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

  }

工作正常。结果是Filepath。但我需要base64string格式。

我该怎么做。

我不知道。

感谢。

2 个答案:

答案 0 :(得分:1)

好的,我所做的与你的方法相似,使用了图片选择器插件,通过这个插件加载了图像,使用图像调整大小插件调整了大小并显示了Base64字符串。

以下是代码:

  getImage() {
    let options = {
      maximumImagesCount: 3,
      width: 400,
      height: 400,
      quality: 90,
      outputType: 0
    };
    this.imagePicker.getPictures(options).then((results) => {
      for (var i = 0; i < results.length; i++) {
        this.imageurlfrompicker = results[i];
        let resizeoptions = {
          uri: results[i],
          folderName: 'demofolder',
          quality: 90,
          width: 1280,
          height: 1280
        } as ImageResizerOptions;
        this.imageResizer
          .resize(resizeoptions)
          .then((filePath: string) => {
            this.imageurlfromresizer = filePath;
            this.convertToBase64(filePath, 'image/png').then(
              data => {
                this.imagebase64 = data.toString();
              }
            );
          })
          .catch(e => console.log(e));
      }
    }, (err) => { });
  }

  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;
    });
  }

屏幕截图:

enter image description here

Get the full working project from my repository

答案 1 :(得分:0)

不确定您是否仍然需要该功能,但它已在图像缩放器中实现,只需尝试类似的操作:

var options = {
  uri: imageURI,
  folderName: "Test Folder",
  fileName: "test.jpg",
  quality: 90,
  width: 1280,
  height: 1280,
  base64: true
};

window.ImageResizer.resize(options,
  function(image) {
    console.log("yeah, resized and it's in base64: ", image)
  }, function() {
    console.log("nope... error!")
  }
);