简体   繁体   中英

Converting an Image url to base64 in Angular

I am struggling trying to convert a given image url to base64... in my case i have a String with the image's path

var imgUrl = `../../../../../assets/logoEmpresas/${empresa.logoUrl}`

how can i convert the given image url in a base64 directly?... i tried this post.

Converting an image to base64 in angular 2

but this post is getting the image from a form... how can i adapt it?

You can use this to get base64 image

async function getBase64ImageFromUrl(imageUrl) {
  var res = await fetch(imageUrl);
  var blob = await res.blob();

  return new Promise((resolve, reject) => {
    var reader  = new FileReader();
    reader.addEventListener("load", function () {
        resolve(reader.result);
    }, false);

    reader.onerror = () => {
      return reject(this);
    };
    reader.readAsDataURL(blob);
  })
}

Then call it like this

getBase64ImageFromUrl('your url')
    .then(result => testImage.src = result)
    .catch(err => console.error(err));

works like charm in pdfMake and angular

You can use this function to create generate a base64 image

    toDataURL = async (url) => {
    console.log("Downloading image...");
    var res = await fetch(url);
    var blob = await res.blob();

    const result = await new Promise((resolve, reject) => {
      var reader = new FileReader();
      reader.addEventListener("load", function () {
        resolve(reader.result);
      }, false);

      reader.onerror = () => {
        return reject(this);
      };
      reader.readAsDataURL(blob);
    })

    return result
  };

and then call it like this

imageSrcString = await this.toDataURL(imageSrc)

If we're doing this in Angular, we may as well make use of HttpClient and a Service .

Let's go ahead and add the HttpClientModule into our related Module, we'll need this in order to use HttpClient.

@NgModule({
  imports: [HttpClientModule],
  ...
})
export class AppModule {}

Then let's create a generic Image Service, and then ask Angular to inject the HttpClient into our Service.

@Injectable()
export class ImageService {
  constructor(private http: HttpClient) { }
}

Once that's done we can actually create our function in our service

imageUrlToBase64(urL: string) {
  return this.http.get(urL, {
      observe: 'body',
      responseType: 'arraybuffer',
    })
    .pipe(
      take(1),
      map((arrayBuffer) =>
        btoa(
          Array.from(new Uint8Array(arrayBuffer))
          .map((b) => String.fromCharCode(b))
          .join('')
        )
      ),
    )
}

When we use http. get and provide arraybuffer as our response type , Angular interprets the body of our request as an ArrayBuffer . What that means is that we'll now have our image as an ArrayBuffer . All we need to do is then convert our ArrayBuffer to a base64 string. If you'd like to view alternative options, this SO Question has good answers.

map(
  btoa(
    Array.from(new Uint8Array(arrayBuffer))
    .map((b) => String.fromCharCode(b))
    .join('')
  )
)

Now that the function is done, we can shift to usage:

@Component()
export class AppComponent {
  base64Image: string;
  constructor(private imageService: ImageService) {
      this.imageService.imageUrlToBase64('https://picsum.photos/200/300').subscribe(
          base64 => {
              this.base64Image = base64
      })
  }
}

We'll now have access to the image as a base64

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM