Home Web Front-end uni-app How to customize photo albums in uniapp

How to customize photo albums in uniapp

May 22, 2023 pm 12:34 PM

With the popularity of mobile devices, photo albums have become an indispensable part of mobile phone users' lives. In application development, how to customize photo albums? This article will introduce you to how to customize photo albums in uniapp.

1. Basic use of photo albums in uniapp

There are two basic ways to use photo albums in uniapp:

  1. Configure permissions in the manifest.json file, use The uni.chooseImage() method calls the photo album:
//manifest.json
"android": {
  "permissions": [
    "android.permission.READ_EXTERNAL_STORAGE",
    "android.permission.WRITE_EXTERNAL_STORAGE"
  ]
}
//业务逻辑
uni.chooseImage({
  count: 1, //选择图片数量,选填,默认9
  success: function(res) {
    console.log(res)
  }
});
Copy after login
  1. Add the tag in the template and obtain the image through the fileChange event:
<template>
  <view>
    <input type="file" accept="image/*" @change="fileChange"/>
  </view>
</template>

<script>
export default {
  data() {
    return {};
  },
  methods: {
    fileChange(e) {
      console.log(e.target.files[0]);
    }
  }
};
</script>
Copy after login

The above two methods are basic ways to use photo albums, but in some business scenarios it may be necessary to implement some customized functions.

2. Customization function of photo album in uniapp

  1. Control the scaling ratio of album pictures

The default scaling ratio of uniapp is 1:1, there are Sometimes we need to control the zoom ratio when selecting an image. This can be achieved by setting the value of the compress option in the count and chooseImage hook functions:

uni.chooseImage({
  count: 1,
  compress: {
    //设置缩放比例为16:9
    width: 640,
    height: 360,
    compressType: 'image/jpeg',
    quality: 90
  },
  success: function(res) {
    console.log(res)
  }
});
Copy after login
  1. Sort by shooting time

In some photo album applications, pictures are sorted according to the time they were taken. Uniapp sorts by file name by default, so you need to implement the logic of sorting by shooting time yourself.

First you need to get the shooting time of the picture. You can use the exif.js library to read the shooting time in the exif information of the picture.

import ExifReader from 'exif-js';

const file = files[0];
const reader = new FileReader();
reader.readAsArrayBuffer(file);
reader.onload = () => {
  //解析exif信息获取拍摄时间
  const tags = ExifReader.load(reader.result);
  const date = tags?.DateTimeOriginal?.value;
};
Copy after login

Next, add the obtained shooting time to an array, and bind the image index and shooting time together:

const arr = [];
for (let i = 0; i < res.tempFilePaths.length; i++) {
  const filePath = res.tempFilePaths[i];
  const file = files[i];
  const reader = new FileReader();
  reader.readAsArrayBuffer(file);
  reader.onload = () => {
    //解析exif信息获取拍摄时间
    const tags = ExifReader.load(reader.result);
    const date = tags?.DateTimeOriginal?.value;
    //绑定图片索引和拍摄时间
    arr.push({ index: i, date });
    if (arr.length === res.tempFilePaths.length) {
      //按拍摄时间排序
      const newArr = arr.sort((a, b) => new Date(b.date) - new Date(a.date));
      const tempFilePaths = newArr.map((item) => res.tempFilePaths[item.index]);
      console.log(tempFilePaths);
    }
  };
}
Copy after login

This way you can sort by shooting time Functional.

  1. Select multiple pictures and stitch them into one picture

In some specific scenarios, it is necessary to allow users to select multiple pictures and stitch them into one picture. At this time, you need to use canvas to stitch together multiple pictures.

First, you need to get multiple pictures selected by the user and draw them on the canvas:

let canvas = document.createElement('canvas');
let ctx = canvas.getContext('2d');
//设置canvas的大小,假设最多允许选取4张图片,宽度为窗口的一半,高度为宽度的0.6倍
canvas.width = document.documentElement.clientWidth / 2;
canvas.height = canvas.width * 0.6;
let x = 0;
let y = 0;
for (let i = 0; i < this.tempFilePaths.length; i++) {
  let img = new Image();
  img.src = this.tempFilePaths[i];
  //等待所有图片都加载完成
  img.onload = () => {
    //绘制图片
    ctx.drawImage(img, x, y, canvas.width / 2, canvas.height / 2);
    //根据图片数量分别计算下一张图片在canvas中的位置
    if (i === 0) {
      x += canvas.width / 2;
    } else if (i === 1) {
      x -= canvas.width / 2;
      y += canvas.height / 2;
    } else if (i === 2) {
      x += canvas.width / 2;
    }
    //当所有图片都绘制完毕后,将canvas转换为图片
    if (i === this.tempFilePaths.length - 1) {
      let tempFilePath = canvas.toDataURL();
    }
  };
}
Copy after login

With the above code, you can splice the selected pictures into one picture.

4. Summary

Through the introduction of this article, I believe you can already understand how to customize photo albums in uniapp, including controlling the zoom ratio of pictures, sorting by shooting time, multiple selection of pictures and stitched together into one picture.

For developing mobile applications, photo albums are a very common function. Mastering the customization skills of photo albums can better improve the user experience of the application. I hope this article can be helpful to everyone.

The above is the detailed content of How to customize photo albums in uniapp. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What are the different types of testing that you can perform in a UniApp application? What are the different types of testing that you can perform in a UniApp application? Mar 27, 2025 pm 04:59 PM

The article discusses various testing types for UniApp applications, including unit, integration, functional, UI/UX, performance, cross-platform, and security testing. It also covers ensuring cross-platform compatibility and recommends tools like Jes

How can you reduce the size of your UniApp application package? How can you reduce the size of your UniApp application package? Mar 27, 2025 pm 04:45 PM

The article discusses strategies to reduce UniApp package size, focusing on code optimization, resource management, and techniques like code splitting and lazy loading.

What debugging tools are available for UniApp development? What debugging tools are available for UniApp development? Mar 27, 2025 pm 05:05 PM

The article discusses debugging tools and best practices for UniApp development, focusing on tools like HBuilderX, WeChat Developer Tools, and Chrome DevTools.

How can you use lazy loading to improve performance? How can you use lazy loading to improve performance? Mar 27, 2025 pm 04:47 PM

Lazy loading defers non-critical resources to improve site performance, reducing load times and data usage. Key practices include prioritizing critical content and using efficient APIs.

How can you optimize images for web performance in UniApp? How can you optimize images for web performance in UniApp? Mar 27, 2025 pm 04:50 PM

The article discusses optimizing images in UniApp for better web performance through compression, responsive design, lazy loading, caching, and using WebP format.

What are some common patterns for managing complex data structures in UniApp? What are some common patterns for managing complex data structures in UniApp? Mar 25, 2025 pm 02:31 PM

The article discusses managing complex data structures in UniApp, focusing on patterns like Singleton, Observer, Factory, and State, and strategies for handling data state changes using Vuex and Vue 3 Composition API.

What are computed properties in UniApp? How are they used? What are computed properties in UniApp? How are they used? Mar 25, 2025 pm 02:23 PM

UniApp's computed properties, derived from Vue.js, enhance development by providing reactive, reusable, and optimized data handling. They automatically update when dependencies change, offering performance benefits and simplifying state management co

How does UniApp handle global configuration and styling? How does UniApp handle global configuration and styling? Mar 25, 2025 pm 02:20 PM

UniApp manages global configuration via manifest.json and styling through app.vue or app.scss, using uni.scss for variables and mixins. Best practices include using SCSS, modular styles, and responsive design.

See all articles