【问题标题】:How to reduce image size significantly before upload in in Ionic4 (Cordova)?在 Ionic4 (Cordova) 中上传之前如何显着减小图像大小?
【发布时间】:2019-08-13 14:58:21
【问题描述】:

如今,手机拍摄的图片尺寸太大,我们无法简单地将这些图片上传到服务器。例如,在我的手机 Redmi Note 7 Pro 中,我得到的图像大小在 15MB20MB 之间。

我正在使用Ionic4 构建一个移动应用程序。在我的应用程序中,我要求用户上传个人资料图片。要上传个人资料图片,用户可以从图库中选择图片,然后提示他裁剪窗口。裁剪后,我们得到 DataUri。从那里,我们将图片上传到服务器。

在服务器上,我添加了验证以验证图像大小不应大于500KB。现在,大多数时候在从画廊上传图片时,我都会看到这个图片尺寸验证错误。这意味着,即使在裁剪图像之后,尺寸也不会减小到500KB。我正在使用的代码如下。

我很确定,这是每个处理图像的移动应用程序的基本需求。任何人都可以在上传之前为我提供显着减小图像大小的正确方法吗?这样,我将在服务器上存储轻量级图像,并且在上传期间有效负载大小也会很小。

edit-profile-component.ts

import { Component, OnInit, OnDestroy } from '@angular/core';
import { UserModel } from 'app/modules/core/models/user-model';
import { ProfilePictureUrlModel } from 'app/modules/core/models/input-models/profile-picture-url-model';
import { AccountService } from 'app/modules/core/services/account.service';
import { ActionSheetController, LoadingController, ToastController, NavController } from '@ionic/angular';
import { ImagePicker } from '@ionic-native/image-picker/ngx';
import { Crop } from '@ionic-native/crop/ngx';
import { Camera, CameraOptions } from '@ionic-native/Camera/ngx';
import { AppConstants } from 'app/config/app.constants';
import { ImageUploadService } from 'app/modules/core/services/image-upload.service';
import { AppError } from 'app/modules/core/models/app-error';
import { AlertService } from 'app/modules/core/services/alert.service';
import { LoadingService } from 'app/modules/core/services/loading.service';
import { Subscription } from 'rxjs';
import { ImageType } from 'app/modules/core/models/enums';
import { DataTransferService } from 'app/modules/core/services/data.transfer.service';

@Component({
  selector: 'app-edit-profile',
  templateUrl: './edit-profile.component.html',
  styleUrls: ['./edit-profile.component.scss'],
})
export class EditProfileComponent implements OnInit, OnDestroy {

  loggedInUser: UserModel;
  subscription1: Subscription;
  subscription2: Subscription;

  constructor(private accountService: AccountService, private actionSheetController: ActionSheetController,
              private imagePicker: ImagePicker,  private crop: Crop,
              private imageUploadService: ImageUploadService,  private alertService: AlertService,
              private loadingService: LoadingService,  private toastController: ToastController,
              private navController: NavController, private dataTransferService: DataTransferService) { }

  ngOnInit() {
    this.loggedInUser = this.accountService.getLoggedInUser();
  }

  ngOnDestroy(): void {
    if (this.subscription1) {
      this.subscription1.unsubscribe();
    }
    if (this.subscription2) {
      this.subscription2.unsubscribe();
    }
  }

  openMyListing() {
    this.navController.navigateForward(AppConstants.Routes.MyListings);
  }

  async showChangeProfilePictureOptions() {
    const actionSheet = await this.actionSheetController.create({
      header: 'Profile photo',
      buttons: [{
        text: 'Gallery',
        icon: 'photos',
        handler: () => {
          this.imagePicker.getPictures({ maximumImagesCount: 1, outputType: 0 }).then((results) => {
            if (results.length > 0) {
             this.crop.crop(results[0], { quality: 100, targetHeight: 400, targetWidth: 400  }).then(newImage => {
                // 1. Show loading circle
                this.loadingService.showLoading('Updating profile picture..');

                // 2. update profile picture
                this.subscription1 =  this.imageUploadService.uploadProfilePicture(newImage, this.loggedInUser.id).subscribe((response) => {
                  if (response.success) {
                    this.subscription2 = this.accountService.uploadUserProfilePicture({
                        imageType: ImageType.UserProfilePicture,
                        filePathToSave: response.data.filePathToSave
                      } as ProfilePictureUrlModel).subscribe(childResponse => {
                        if (childResponse.success) {

                          // 1. Update profile picture on current page
                          this.loggedInUser.profilePicture = response.data.httpFilePath;

                          // 2. update profile picture in local storage
                          this.accountService.updateProfilePictureInLocalStorage(response.data.httpFilePath);

                          // 3. update profile picture in side menu
                          this.dataTransferService.updateUpdatedUserProfilePicture(response.data.httpFilePath);

                          // 4. show success notification
                          this.toastController.create({
                            position: 'bottom',
                            message: 'Profile picture updated successfully.',
                            duration: 2000
                          }).then((item) => {
                            item.present();
                          });

                        } else {
                          this.alertService.showHandledError(response);
                        }
                      }, (error: any) => { throw error; });
                    } else {
                      this.alertService.showHandledError(response);
                    }
                }, (error: any) => { throw error; });

                // 3. hide loading
                this.subscription1.add(() => {
                  if (this.subscription2) {
                    this.subscription2.add(() => {
                      this.loadingService.hideLoading();
                    });
                  } else {
                    this.loadingService.hideLoading();
                  }
                });
             }).catch(error => { throw error; });
            }
          }).catch(error => { throw error; });
        }
      }]
    });
    await actionSheet.present();
  }
}

【问题讨论】:

    标签: cordova ionic-framework ionic2 ionic3 ionic4


    【解决方案1】:

    将这些传递给选项质量意味着图像质量

     { quality: 50, targetHeight: 400, targetWidth: 400  }
    

    https://ionicframework.com/docs/native/camera

    const options: CameraOptions = {
      quality: 100,<--- image quality
      destinationType: this.camera.DestinationType.FILE_URI,
      encodingType: this.camera.EncodingType.JPEG,
      mediaType: this.camera.MediaType.PICTURE
    }
    
        this.camera.getPicture(options).then((imageData) => {
         // imageData is either a base64 encoded string or a file URI
         // If it's base64 (DATA_URL):
         let base64Image = 'data:image/jpeg;base64,' + imageData;
        }, (err) => {
         // Handle error
        });
    

    【讨论】:

    • 如果我们将质量设置为50。是否意味着尺寸将缩小到一半或可能会缩小到实际尺寸的一半以上?
    • 它减少了一半
    • 图像质量 50%
    • 尺寸也缩小了
    猜你喜欢
    • 1970-01-01
    • 2021-08-19
    • 1970-01-01
    • 2017-05-27
    • 1970-01-01
    • 1970-01-01
    • 2020-06-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多