What is the best way to showcase pictures retrieved from Cordova PhotoLibrary?

I've encountered an issue with displaying images in the Image Gallery on my Android device. Although the PhotoLibrary plugin successfully returns a list of image URLs, I am having difficulty loading them into img tags.

            window['cordova']['plugins']['photoLibrary'].getLibrary(
                result => console.log(libraryItem),
                err => console.log(err);
                },
                {
                    thumbnailWidth: 512,
                    thumbnailHeight: 384,
                    quality: 0.8,
                    includeAlbumData: true
                });

While this code retrieves the image URLs, I'm unable to actually display them. The data returned looks like:

creationDate: Fri Nov 03 2017 20:06:01 GMT-0400 (EDT)
fileName: "2017-10-4-1.jpg"
height: 960
id: "1907;/storage/emulated/0/Pictures/Timelapser/2017-10-4-1.jpg"
latitude: 0
longitude: 0
photoURL: "cdvphotolibrary://photo?photoId=1907%3B%2Fstorage%2Femulated%2F0%2FPictures%2FTimelapser%2F2017-10-4-1.jpg"
thumbnailURL: "cdvphotolibrary://thumbnail?photoId=1907%3B%2Fstorage%2Femulated%2F0%2FPictures%2FTimelapser%2F2017-10-4-1.jpg&width=512&height=384&quality=0.8"
width: 1280

Attempts to use photoURL or thumbnailURL in the img src attribute have been unsuccessful. I've tried decoding the URL, using different parts of the link, but nothing seems to work.

Answer №1

To integrate the Native Photo Library plugin, you will need to utilize the cdvphotolibrary pipe as demonstrated below.

For a functional example, refer to this Git project.

html

<ion-grid no-padding margin-top>
    <ion-row class="row">
      <ion-col col-6 *ngFor="let data of library">
        <img [src]="data?.thumbnailURL | cdvPhotoLibrary">
      </ion-col>
    </ion-row>
  </ion-grid>

ts

// Fetch Photos
fetchPhotos() {
    this.platform.ready().then(() => {
      this.library = [];

      this.photoLibrary.getLibrary({ thumbnailWidth: THUMBNAIL_WIDTH, thumbnailHeight: THUMBNAIL_HEIGHT }).subscribe({
        next: (chunk) => {
          this.library = this.library.concat(chunk);
          this.cd.detectChanges();
        },
        error: (err: string) => {
          if (err.startsWith('Permission')) {
            this.platform.ready().then(() => {
              this.photoLibrary.requestAuthorization({ read: true })
                .then(() => {
                }).catch((err) => {
                  let message = 'requestAuthorization error: ${err}';
                  this.showToast.showErrorToast(message);
                });
            });
          } else { // Real error
            let message: 'getLibrary error: ${err}';
            this.showToast.showErrorToast(message);
          }
        },
        complete: () => {
          // Library completely loaded
        }
      });
    });
  }

cdv-photo-library.ts (pipe)

import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';

@Pipe({
  name: 'cdvPhotoLibrary',
})
export class CdvPhotoLibraryPipe implements PipeTransform {

  constructor(private sanitizer: DomSanitizer) { }

  transform(url: string) {
    if (url != null) {
      return url.startsWith('cdvphotolibrary://') ? this.sanitizer.bypassSecurityTrustUrl(url) : url;
    }
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Discovering React Styled Components Within the DOM

While working on a project using Styled Components in React, I have successfully created a component as shown below: export const Screen = styled.div({ display: "flex", }); When implementing this component in my render code, it looks like this ...

Exploring the Children Property in TypeScript and the Latest Version of React

Within my App.tsx file, I am passing <Left /> and <Right /> as components to an imported component named <SplitScreen />. It seems that in React 18, the "children" prop needs to be explicitly typed. When I type it as React.Element[], eve ...

Discover the perfect way to implement true lazyloading using NativeScript Angular tabs and BottomNavigation

Currently working on an app using nativescipt, I've successfully added BottomNavigation with lazy loading and Tab components in child pages. The code structure resembles the following: export const routes: Routes = [ { path: '', red ...

The 'undefined' type cannot be assigned to the '(number | null)[]' type

I recently encountered an issue with the following code snippet: const data = values?.map((item: PointDTO) => item.y); const chartData: ChartData = { labels, datasets: [{ data }], }; The error message I received is as follows: Type '(number | ...

Uploading images using the power of Angular and Node.js

I have been struggling with a persistent issue for quite some time now, and I have not been able to find a solution anywhere. My goal is to allow users to update their avatars on their profiles. However, every time I attempt to pass the file to my node ser ...

When the admin clicks the start button, redirect all users to the designated page

Currently, I am developing a voting application that features both an admin and users. My goal is for the voting campaign to kick off as soon as the admin clicks on the start button. Upon starting the voting process, I aim to redirect all users to a diff ...

Incorporate dynamic HTML snippets into the DOM with Angular 4

Looking to populate an unordered list element <ul> with small, straightforward snippets from my JavaScript. Just basic lines like <li>Label: Text</li>. Using the ViewContainerRef.createComponent(ItemComponent) method to create a new comp ...

Error: The page "..." contains an invalid "default" export. The type "..." is not recognized in Next.js

Currently, I have a functional component set up for the Signup page. My goal is to define props within this component so that I can pass the necessary values to it from another component. This is my current approach: export default function SignupPage({mod ...

Issue with Angular 4: 'HttpClient' name not found

While attempting to access a JSON feed, I followed the guidelines outlined in the documentation, but encountered the following error: "Cannot find name 'HttpClient'" Despite reviewing the tutorial multiple times, I am struggling to pinpoint t ...

The takeUntil function will cancel an effect request if a relevant action has been dispatched before

When a user chooses an order in my scenario: selectOrder(orderId): void { this.store$.dispatch( selectOrder({orderId}) ); } The order UI component triggers an action to load all associated data: private fetchOrderOnSelectOrder(): void { this.sto ...

Modify the selection in one dropdown menu based on the selection in another dropdown menu using Angular 8

When I have two dropdowns, I aim to update the second dropdown with a matching JSON object based on the value selected in the first dropdown. JSON this.dropdownValues = { "mysql 8": { "flavor": [ "medium", ...

Performance challenges with rendering SVG in ngFor due to the presence of a highly nested array structure - in

I'm currently developing a business application that requires me to dynamically render SVG images for displaying floor plans. The SVG elements are stored in a database and provided to the front-end in JSON format, allowing the graphics to be rendered ...

"Retrieve the x-coordinate position of a box within a specific div using

https://i.sstatic.net/68yeF.jpg https://i.sstatic.net/ZCrxZ.jpg Is there a way for me to move the box within the gray area? <div id="timeline"> <div cdkDragBoundary="#timeline" ...

The system is unable to convert the lengthy error message into a valid Element Room Database structure

I'm currently in the process of implementing cache functionality for my project using Room, but I've encountered an issue. I previously used it successfully with a simpler model, however, when working with a more complex model, I'm facing a ...

Angular 8: Setting the Default Dropdown Option to the Newest Value in the Updated ArrayList

I am currently working with Angular 8 and TypeScript. After calling a service and updating the array collection, I want to automatically select the last aggregated value. However, I always want the placeholder to be shown. How can I achieve this? <nb- ...

Is it possible to create a nested object inside of an array?

Looking to accomplish the following: let listOne: any = ['item1', 'item2', 'item3']; let details: any; // Previously, I had a loop running and 'row' was the response outputting items // in the listOne array const ...

Employ Regular Expression in Android to extract phone numbers from website text data

I am trying to save text data from a website onto my memory card. Once saved, I want to implement regular expressions to extract a phone number. Below is the code I am currently using to fetch the website: public void onCreate(Bundle savedInstanceState) ...

Using the amDateFormat pipe in Ionic 3's Lazy Loading feature

Currently, I am using Ionic3 and working on transitioning to Lazy Loading to enhance the startup performance. Since converting my ChatsPage to lazy loading, I have encountered an issue with pipes. The error message points to a specific line in my chats.ht ...

What would be the best dimension for an Angular 11 module?

Picture yourself developing a brand new modular app in Angular and facing the decision of when to create a new module. Is it considered best practice to create a module per page if the pages do not have common components? Is there an optimal size for Ang ...

The error message "TypeError: Attempting to access the 'map' property of an undefined value (React JS)" was displayed

I'm currently working on a recursive function that needs to iterate over an object type called ItemType. However, I encountered an error message: TypeError: Cannot read property 'map' of undefined This is the code snippet causing the issue: ...