2

I am following a tutorial on Ionic/Capacitor with Angular and this part here is causing me some problems:

Plugins.Camera.getPhoto({
  quality: 50,
  source: CameraSource.Prompt,
  correctOrientation: true,
  width: 200,
  resultType: CameraResultType.Base64
})
  .then(image => {
    this.selectedImage = image.base64String;

With the template accessing selectedImage pretty straightforwardly, like this:

  <ion-img
          role="button"
          class="image"
          (click)="onImagePicked()"
          [src]="selectedImage"
          *ngIf="selectedImage"
  ></ion-img>

In particular I get this runtime/browser error upon taking the picture: net::ERR_CONNECTION_RESET 431 (Request Header Fields Too Large) with the URL called by ionic being http://localhost:4200/HUGE_BASE64_STRING

Now I thought the problem might be storing the image as base64 instead of a blob in memory. But then I came across this question:

Convert blob to base64

So if I did

 var reader = new FileReader();
 reader.readAsDataURL(blob); 
 reader.onloadend = function() {
     var base64data = reader.result;                
 }

I would still convert the image to a huge URL this way, no? So what is the proper way to store a big image locally?

I assume this is a general JS question, not an ionic specific one, hence the JS tag

Phil
  • 7,065
  • 8
  • 49
  • 91

3 Answers3

7

Setting the right prefix solved the problem; when you retrieve a base64 it should have a prefix like this, otherwise some frameworks might prepend a base-url to it:

    this.selectedImage = 'data:image/jpeg;base64,' + image.base64String;
Phil
  • 7,065
  • 8
  • 49
  • 91
0

The tutorial you are following is out of date, Check the docs and this official tutorial

Base64 just return the base64 data, that can’t be displayed in an img tag as you have figured out.

But there is DataUrl result type, which returns a proper data url you can use to display in the img tag.

jcesarmobile
  • 51,328
  • 11
  • 132
  • 176
0

Checkout SourceCode on https://github.com/ionic-team/capacitor/blob/fc1150a1d2fe15d2ece34507c1deae4eb8b6b028/core/src/web/camera.ts#L46

If you specify resultType: CameraResultType.Uri

The plugin Will URL.createObjectURL(PhotoBlob)

(*aprox: Take the PhotoBlob and create a url that Will serve it from memory) So you only have to atach that to the src of the img.

If you use FileReader.readAsDataURL() The plugin Will read the camera stream and produce a Base64 data url like (data:content.typeOfImage/base64) that you could also put on src field, then the img Will decode the string and render it.

If you use CameraResultType.Base64 The plugin Will read the camera stream and produce only the base64 string not the data url. If you know the content-type of the image you could produce the data url by concatenation and have (data:content.typeOfImage/base64).

dolpsdw
  • 78
  • 5