zhengyiming
2025-02-13 4b144a96077786b90d56abf1e23e41e7d5a11aa7
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
<template>
  <PreviewImage :mode="openScale ? 'scaleToFill' : 'widthFix'" :style="_style" v-bind="omitProps" />
</template>
 
<script setup lang="ts">
import PreviewImage from './PreviewImage.vue';
import { previewImageProps } from './previewImage';
import Taro from '@tarojs/taro';
import { CSSProperties, computed, reactive, watch } from 'vue';
import _ from 'lodash';
 
defineOptions({
  name: 'AutoWidthImage',
});
 
const props = defineProps({
  ...previewImageProps,
  openScale: {
    type: Boolean,
  },
});
 
const omitProps = computed(() => _.omit(props, ['openScale']));
 
const MaxHeight = 200;
const MaxWidth = 200;
 
const state = reactive({
  width: 0,
  height: 0,
});
 
watch(
  () => props.src,
  () => {
    if (props.src) {
      Taro.getImageInfo({
        src: props.src,
        success(result) {
          state.width = result.width;
          state.height = result.height;
        },
      });
    }
  },
  {
    immediate: true,
  }
);
 
const _style = computed(() => {
  if (state.width > state.height) {
    if (props.openScale) {
      const width = Math.min(MaxWidth, state.width);
      const scale = width / state.width;
 
      return {
        height: `${state.height * scale}px`,
        width: `${width}px`,
      } as CSSProperties;
    } else {
      return {
        width: `${state.width}px`,
        maxWidth: '100%',
      };
    }
  } else {
    const height = Math.min(MaxHeight, state.height);
    const scale = height / state.height;
    return {
      height: `${height}px`,
      width: `${state.width * scale}px`,
    } as CSSProperties;
  }
});
</script>
 
<style lang="scss">
@import '@/styles/common.scss';
 
.auto-width-image-wrapper {
  width: auto !important;
  height: auto !important;
}
</style>