How can I showcase the captured image on Ionic 2?

I am having trouble displaying the selected or captured image on the page after uploading it through two methods - one using the gallery and the other using the camera.

** Here is my code **

1) profile.html:

<img class="profile-picture" src="{{baseUrl + 'service/renderImage/' + 
         profId}}" (click)="changePicture()">
<h6 secondary>{{ 'TAP_ON_IMAGE' | translate }}</h6>

2) profile.ts:

import { Component } from '@angular/core';
import { PhotoViewer, ActionSheet, Camera, Transfer, Base64ToGallery } from 'ionic-native';
import { NavController, Platform, NavParams, AlertController } from 'ionic-angular';
import { LogDetails, ProfileDetails, serviceUrl } from '../../services/root-scope';
import { Http } from '@angular/http';
import { HomePage } from '../home/home';
import { TranslateService } from '@ngx-translate/core';

@Component({
selector: 'page-profile',
templateUrl: 'profile.html'
})
export class ProfilePage {
base64Image: string;
public profId: any;
public baseUrl: any;
public data: any;
public translate: any;
constructor(public navCtrl: NavController, http: Http, public navParams: NavParams, public alertCtrl: AlertController, translate: TranslateService) 
{
this.profId = ProfileDetails.profileId;
this.baseUrl = serviceUrl.baseUrl;
this.translate = translate;
this.data = {};
}
//this is my function
 changePicture() {
    console.log("changePicture called");
    let buttonLabels = [this.translate.get("VIEW_IMAGE").value, this.translate.get("CHANGE_IMAGE").value];
    ActionSheet.show({
        'title': this.translate.get("WHAT_DO_YOU_WANT_WITH_THIS_IMAGE").value,
        'buttonLabels': buttonLabels,
        'addCancelButtonWithLabel': this.translate.get("CANCEL").value,
        'addDestructiveButtonWithLabel': this.translate.get("DELETE").value
    }).then((buttonIndex: number) => {
        //alert('Button pressed: ' + buttonIndex);
        if (buttonIndex == 2) {
            try {
                /*Base64ToGallery.base64ToGallery(this.baseUrl + 'service/renderImage/' + this.profId, 'img_').then(
                    res => {
                        console.log('Saved image to gallery ', res);
                        PhotoViewer.show(res, this.name, { share: true })
                    },
                    err => {
                        console.log('Error saving image to gallery ', err);
                    }
                );*/
                PhotoViewer.show(this.baseUrl + 'service/renderImage/' + this.profId, this.name, { share: false })
            }
            catch (err) {
                console.log("Error in rendering image : "+err.message);
            }
        }
        else if(buttonIndex == 3) {
            //alert("buttonIndex : " + buttonIndex);
            let alert = this.alertCtrl.create();
            alert.setTitle(this.translate.get("CHOOSE_PHOTO_TYPE").value);

            alert.addInput({
                type: 'radio',
                label: this.translate.get("CAMERA").value,
                value: '1',
                checked: true
            });

            alert.addInput({
                type: 'radio',
                label: this.translate.get("GALLERY").value,
                value: '2',
                checked: false
            });

            alert.addButton(this.translate.get("CANCEL").value);
            alert.addButton({
                text: this.okBtn,
                handler: data => {
                    console.log("received data : ", data);
                    var options;
                    if (data == '1') {
                        options = {
                            allowEdit: true,
                            correctOrientation: true,
                            saveToPhotoAlbum: true
                        }
                    }
                    else if (data == '2') {
                        options = {
                            sourceType: 2,
                            allowEdit: true,
                            correctOrientation: true,
                            saveToPhotoAlbum: true
                        }
                    }
                    console.log("options : ", options);

                      Camera.getPicture(options)
                      .then((imageData)=>{
                        this.base64Image = "data:image/jpeg;base64," + imageData;

                        let cameraImageSelector = document.getElementById('camera-image');
                        cameraImageSelector.setAttribute('src', this.base64Image);

                      })
                      .catch(err=>{
                        console.log(err);
                      })
                   }
            });
            alert.present();
        }
    });
}

I want to upload the image using two methods one using gallery & another one using a camera. However, I am facing an issue where the selected or captured image is not displaying on the page.

Thanks in advance!

Answer №1

Give this a shot:

.html

<ion-header>
  <ion-navbar color="primary">
    <ion-title>
      Home
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  <img src="{{pathForImage(lastImage)}}" style="width: 100%" [hidden]="lastImage === null">
  <h3 [hidden]="lastImage !== null">Please Select Image!</h3>
</ion-content>

<ion-footer>
  <ion-toolbar color="primary">
    <ion-buttons>
      <button ion-button icon-left (click)="presentActionSheet()">
        <ion-icon name="camera"></ion-icon>Select Image
      </button>
    </ion-buttons>
  </ion-toolbar>
</ion-footer>

.ts

import { Component } from '@angular/core';
import { NavController, ActionSheetController, ToastController, Platform, LoadingController, Loading } from 'ionic-angular';

import { File } from '@ionic-native/file';
import { Transfer, TransferObject } from '@ionic-native/transfer';
import { FilePath } from '@ionic-native/file-path';
import { Camera } from '@ionic-native/camera';

declare var cordova: any;

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  lastImage: string = null;
  loading: Loading;

  constructor(public navCtrl: NavController, private camera: Camera, private transfer: Transfer, private file: File, private filePath: FilePath, public actionSheetCtrl: ActionSheetController, public toastCtrl: ToastController, public platform: Platform, public loadingCtrl: LoadingController) { }

  public presentActionSheet() {
    let actionSheet = this.actionSheetCtrl.create({
      title: 'Select Image Source',
      buttons: [
        {
          text: 'Load from Library',
          handler: () => {
            this.takePicture(this.camera.PictureSourceType.PHOTOLIBRARY);
          }
        },
        {
          text: 'Use Camera',
          handler: () => {
            this.takePicture(this.camera.PictureSourceType.CAMERA);
          }
        },
        {
          text: 'Cancel',
          role: 'cancel'
        }
      ]
    });
    actionSheet.present();
  }

  public takePicture(sourceType) {
  // Create options for the Camera Dialog
  var options = {
    quality: 100,
    sourceType: sourceType,
    saveToPhotoAlbum: false,
    correctOrientation: true
  };

  // Get the data of an image
  this.camera.getPicture(options).then((imagePath) => {
    // Special handling for Android library
    if (this.platform.is('android') && sourceType === this.camera.PictureSourceType.PHOTOLIBRARY) {
      this.filePath.resolveNativePath(imagePath)
        .then(filePath => {
          let correctPath = filePath.substr(0, filePath.lastIndexOf('/') + 1);
          let currentName = imagePath.substring(imagePath.lastIndexOf('/') + 1, imagePath.lastIndexOf('?'));
          this.copyFileToLocalDir(correctPath, currentName, this.createFileName());
        });
    } else {
      var currentName = imagePath.substr(imagePath.lastIndexOf('/') + 1);
      var correctPath = imagePath.substr(0, imagePath.lastIndexOf('/') + 1);
      this.copyFileToLocalDir(correctPath, currentName, this.createFileName());
    }
  }, (err) => {
    this.presentToast('Error while selecting image.');
  });
}

// Create a new name for the image
private createFileName() {
  var d = new Date(),
  n = d.getTime(),
  newFileName =  n + ".jpg";
  return newFileName;
}

// Copy the image to a local folder
private copyFileToLocalDir(namePath, currentName, newFileName) {
  this.file.copyFile(namePath, currentName, cordova.file.dataDirectory, newFileName).then(success => {
    this.lastImage = newFileName;
  }, error => {
    this.presentToast('Error while storing file.');
  });
}

private presentToast(text) {
  let toast = this.toastCtrl.create({
    message: text,
    duration: 3000,
    position: 'top'
  });
  toast.present();
}

// Always get the accurate path to your apps folder
public pathForImage(img) {
  if (img === null) {
    return '';
  } else {
    return cordova.file.dataDirectory + img;
  }
}
}

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

How can one address the issue of Error inflating class android.support.design.widget.BottomNavigationView?

Having trouble implementing the Bottom Navigation view method. I keep getting an error when running my code: Caused by: android.view.InflateException: Binary XML file line #19: Binary XML file line #19: Error inflating class android.support.design.widget. ...

Stopping or pausing an HTML5 audio element in Angular with component.ts

Is there a way to create a custom function in my component.ts file to pause an HTML audio element? I can't seem to find any built-in methods for pausing audio when using document.getElement. <audio controls id="audio-file" > <source src="sam ...

Here is a unique version of the text: "Utilizing Various MAT_DATE_FORMATS

I am facing an issue with multiple date input formats in a component. While most inputs follow the standard MM/DD/YYYY format, one requires a custom format (MM/YYYY). I found guidance here on how to customize the format but now all inputs are displaying wi ...

"Stylish form field design with outlined borders that displays a subtle hover

I am attempting to modify the background color of a mat-form-field outlined when hovering with the mouse. .mat-form-field.mat-form-field-appearance-outline.mat-form-field-outline-thick { // HOVER EFFECT background-color: $dark-blue-200; } The above ...

Trigger a redraw of the Angular Material sidenav

My webpage features two Angular Material sidenavs. However, the website's CSS includes an @media query: @media (max-width: 1440px) { mat-sidenav { width: 300px; } } When the screen width changes without a page reload, I notice a gap ...

Automatically injecting dependencies in Aurelia using Typescript

Recently, I started working with Typescript and Aurelia framework. Currently, I am facing an issue while trying to implement the @autoinject decorator in a VS2015 ASP.NET MVC 6 project. Below is the code snippet I am using: import {autoinject} from "aure ...

Error: The React Native code is unable to access the property 'CameraType' because it is undefined

I'm experiencing issues with my app crashing on an Android device when trying to utilize the expo-camera for camera features. Here is a snippet of my JavaScript code: import React, { useState, useEffect, useRef } from 'react'; import { Text, ...

Cross-Origin Resource Sharing Problem - Angular version 8 with NodeJS and ExpressJS

I've attempted various solutions from different sources and have a feeling that I may be overlooking something minor here. In my setup, I have an AngularJS 8 application running on Node 10 with ExpressJS. The specific issue I'm encountering rela ...

Develop React Native SDKs natively

I am looking to develop client libraries for my backend that will be utilized on iOS and Android platforms. These libraries will need to interact with native services such as location services. Instead of building separate SDKs for both platforms, I am co ...

The functionality of Angular 8 Directives from the shared module is currently malfunctioning

Hey everyone! I've been working on creating a custom directive in Angular 8, but for some reason it's not functioning properly. Even though there are no errors shown in the browser console, I can't see any changes or output from the console. ...

The Div element on my webpage is not adjusting properly to fit the size of mobile devices

My app was created using Quick flip 2, and I needed to resize it for mobile screens, so I implemented jquery-mobile. Here is the code snippet: <!--css--> <style> .quickFlip, .quickFlip3 { height: 350px; width: 400px; } .quickFlip2 { ...

What is the rationale behind permitting surplus properties in Typescript interfaces even though all properties are declared as optional?

Exploring the code snippet... interface Options { allowed?: string; } function test(options: Options) { return options; } const options = { allowed: 'allowed', notAllowed: 'notAllowed', }; test(options); // no error thrown ...

Unable to export Interface in Typescript - the specific module does not offer an export named Settings

I am encountering an issue while trying to export/import an interface in Typescript. The error message I receive is causing confusion as I'm unsure of where I went wrong. Uncaught SyntaxError: The requested module '/src/types/settings.ts' ...

Consider the presence of various peer dependency versions in a react-typescript library

Currently, I am in the process of converting my react component library react-esri-leaflet to typescript. This library requires the user to install react-leaflet as a peerDependency and offers support for both react-leaflet version 3 (RLV3) and react-leafl ...

The Standalone Component does not appear for debugging in webpack:source when utilizing an incompatible version of Node

I have developed two components: https://i.sstatic.net/fSNqa.png However, after running ng serve, I am only able to see one component in the source of the Chrome browser: https://i.sstatic.net/VzdDS.png How can I troubleshoot this standalone component? ...

Next.js Pre-rendering Issue: Error encountered when trying to access properties of a null object

Using Next.js for a React application (full code available here.) Encountering an unusual error while running next build, showing errors related to prerendering on five pages: spenc@WhiteBoxu:~/workout-tracker$ next build info - Loaded env from /home/spe ...

Is it possible for FormArray to return null?

Hello there. I've attempted various methods, but none of them seem to be effective. Currently, I am working on this task where I need to start a formArray for emails. email: [testestest] However, what I have is: email: [testestest] I'm encoun ...

Stopping HTTP client calls in OnDestroy hook of an Angular Service

Is it possible to automatically unsubscribe from an http call in an Angular service using the ngOnDestroy hook? Just to note, I am already familiar with using the rxjs 'take' operator or manually unsubscribing from the service within the compone ...

React with TypeScript - Troubleshooting TS Error when Iterating over List Item (LI) Elements

Iterating through a group of <li> elements to strip away a specific class, then applying the same class to a different <li>. See the snippet below: useEffect(() => { if (dnArrowIdx === undefined) { const allLi = Array.from(document. ...

Navigating through different pages in Angular2 using Asp.net 4.5

I am in need of assistance. I recently switched back to using ASP.NET 4.5 from developing with Angular2 and ASP.NET Core, and I am facing a major issue with routing. When I was using ASP.NET Core, redirecting all 404 requests to index.html was simple with ...