about summary refs log tree commit diff
path: root/src/state/models/media/image.ts
blob: e524c49de058905e2e754f3caae85822dd34b6a9 (plain) (blame)
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
import {Image as RNImage} from 'react-native-image-crop-picker'
import {RootStoreModel} from 'state/index'
import {makeAutoObservable, runInAction} from 'mobx'
import {POST_IMG_MAX} from 'lib/constants'
import * as ImageManipulator from 'expo-image-manipulator'
import {getDataUriSize} from 'lib/media/util'
import {openCropper} from 'lib/media/picker'
import {ActionCrop, FlipType, SaveFormat} from 'expo-image-manipulator'
import {Position} from 'react-avatar-editor'
import {Dimensions} from 'lib/media/types'

export interface ImageManipulationAttributes {
  aspectRatio?: '4:3' | '1:1' | '3:4' | 'None'
  rotate?: number
  scale?: number
  position?: Position
  flipHorizontal?: boolean
  flipVertical?: boolean
}

const MAX_IMAGE_SIZE_IN_BYTES = 976560

export class ImageModel implements Omit<RNImage, 'size'> {
  path: string
  mime = 'image/jpeg'
  width: number
  height: number
  altText = ''
  cropped?: RNImage = undefined
  compressed?: RNImage = undefined

  // Web manipulation
  prev?: RNImage
  attributes: ImageManipulationAttributes = {
    aspectRatio: '1:1',
    scale: 1,
    flipHorizontal: false,
    flipVertical: false,
    rotate: 0,
  }
  prevAttributes: ImageManipulationAttributes = {}

  constructor(public rootStore: RootStoreModel, image: Omit<RNImage, 'size'>) {
    makeAutoObservable(this, {
      rootStore: false,
    })

    this.path = image.path
    this.width = image.width
    this.height = image.height
  }

  setRatio(aspectRatio: ImageManipulationAttributes['aspectRatio']) {
    this.attributes.aspectRatio = aspectRatio
  }

  setRotate(degrees: number) {
    this.attributes.rotate = degrees
    this.manipulate({})
  }

  flipVertical() {
    this.attributes.flipVertical = !this.attributes.flipVertical
    this.manipulate({})
  }

  flipHorizontal() {
    this.attributes.flipHorizontal = !this.attributes.flipHorizontal
    this.manipulate({})
  }

  get ratioMultipliers() {
    return {
      '4:3': 4 / 3,
      '1:1': 1,
      '3:4': 3 / 4,
      None: this.width / this.height,
    }
  }

  getUploadDimensions(
    dimensions: Dimensions,
    maxDimensions: Dimensions = POST_IMG_MAX,
    as: ImageManipulationAttributes['aspectRatio'] = 'None',
  ) {
    const {width, height} = dimensions
    const {width: maxWidth, height: maxHeight} = maxDimensions

    return width < maxWidth && height < maxHeight
      ? {
          width,
          height,
        }
      : this.getResizedDimensions(as, POST_IMG_MAX.width)
  }

  getResizedDimensions(
    as: ImageManipulationAttributes['aspectRatio'] = 'None',
    maxSide: number,
  ) {
    const ratioMultiplier = this.ratioMultipliers[as]

    if (ratioMultiplier === 1) {
      return {
        height: maxSide,
        width: maxSide,
      }
    }

    if (ratioMultiplier < 1) {
      return {
        width: maxSide * ratioMultiplier,
        height: maxSide,
      }
    }

    return {
      width: maxSide,
      height: maxSide / ratioMultiplier,
    }
  }

  async setAltText(altText: string) {
    this.altText = altText
  }

  // Only compress prior to upload
  async compress() {
    for (let i = 10; i > 0; i--) {
      // Float precision
      const factor = Math.round(i) / 10
      const compressed = await ImageManipulator.manipulateAsync(
        this.cropped?.path ?? this.path,
        undefined,
        {
          compress: factor,
          base64: true,
          format: SaveFormat.JPEG,
        },
      )

      if (compressed.base64 !== undefined) {
        const size = getDataUriSize(compressed.base64)

        if (size < MAX_IMAGE_SIZE_IN_BYTES) {
          runInAction(() => {
            this.compressed = {
              mime: 'image/jpeg',
              path: compressed.uri,
              size,
              ...compressed,
            }
          })
          return
        }
      }
    }

    // Compression fails when removing redundant information is not possible.
    // This can be tested with images that have high variance in noise.
    throw new Error('Failed to compress image')
  }

  // Mobile
  async crop() {
    try {
      // openCropper requires an output width and height hence
      // getting upload dimensions before cropping is necessary.
      const {width, height} = this.getUploadDimensions({
        width: this.width,
        height: this.height,
      })

      const cropped = await openCropper(this.rootStore, {
        mediaType: 'photo',
        path: this.path,
        freeStyleCropEnabled: true,
        width,
        height,
      })

      runInAction(() => {
        this.cropped = cropped
      })
    } catch (err) {
      this.rootStore.log.error('Failed to crop photo', err)
    }
  }

  // Web manipulation
  async manipulate(
    attributes: {
      crop?: ActionCrop['crop']
    } & ImageManipulationAttributes,
  ) {
    let uploadWidth: number | undefined
    let uploadHeight: number | undefined

    const {aspectRatio, crop, position, scale} = attributes
    const modifiers = []

    if (this.attributes.flipHorizontal) {
      modifiers.push({flip: FlipType.Horizontal})
    }

    if (this.attributes.flipVertical) {
      modifiers.push({flip: FlipType.Vertical})
    }

    if (this.attributes.rotate !== undefined) {
      modifiers.push({rotate: this.attributes.rotate})
    }

    if (crop !== undefined) {
      const croppedHeight = crop.height * this.height
      const croppedWidth = crop.width * this.width
      modifiers.push({
        crop: {
          originX: crop.originX * this.width,
          originY: crop.originY * this.height,
          height: croppedHeight,
          width: croppedWidth,
        },
      })

      const uploadDimensions = this.getUploadDimensions(
        {width: croppedWidth, height: croppedHeight},
        POST_IMG_MAX,
        aspectRatio,
      )

      uploadWidth = uploadDimensions.width
      uploadHeight = uploadDimensions.height
    } else {
      const uploadDimensions = this.getUploadDimensions(
        {width: this.width, height: this.height},
        POST_IMG_MAX,
        aspectRatio,
      )

      uploadWidth = uploadDimensions.width
      uploadHeight = uploadDimensions.height
    }

    if (scale !== undefined) {
      this.attributes.scale = scale
    }

    if (position !== undefined) {
      this.attributes.position = position
    }

    if (aspectRatio !== undefined) {
      this.attributes.aspectRatio = aspectRatio
    }

    const ratioMultiplier =
      this.ratioMultipliers[this.attributes.aspectRatio ?? '1:1']

    const result = await ImageManipulator.manipulateAsync(
      this.path,
      [
        ...modifiers,
        {
          resize:
            ratioMultiplier > 1 ? {width: uploadWidth} : {height: uploadHeight},
        },
      ],
      {
        base64: true,
        format: SaveFormat.JPEG,
      },
    )

    runInAction(() => {
      this.cropped = {
        mime: 'image/jpeg',
        path: result.uri,
        size:
          result.base64 !== undefined
            ? getDataUriSize(result.base64)
            : MAX_IMAGE_SIZE_IN_BYTES + 999, // shouldn't hit this unless manipulation fails
        ...result,
      }
    })
  }

  resetCropped() {
    this.manipulate({})
  }

  previous() {
    this.cropped = this.prev
    this.attributes = this.prevAttributes
  }
}