Page Menu
Home
Phorge
Search
Configure Global Search
Log In
Files
F85949302
No One
Temporary
Actions
View File
Edit File
Delete File
View Transforms
Subscribe
Mute Notifications
Flag For Later
Award Token
Authored By
Unknown
Size
8 KB
Referenced Files
None
Subscribers
None
View Options
diff --git a/changelog.d/compress-only-smaller.fix b/changelog.d/compress-only-smaller.fix
new file mode 100644
index 0000000000..26bad5c3bc
--- /dev/null
+++ b/changelog.d/compress-only-smaller.fix
@@ -0,0 +1 @@
+Compressed pictures are uploaded only when they got smaller. The original keeps its metadata (EXIF) then, which the canvas used to remove
diff --git a/src/components/media_upload/media_upload.js b/src/components/media_upload/media_upload.js
index cead5b9951..0e07626800 100644
--- a/src/components/media_upload/media_upload.js
+++ b/src/components/media_upload/media_upload.js
@@ -1,183 +1,188 @@
import fileSizeFormatService from '../../services/file_size_format/file_size_format.js'
import statusPosterService from '../../services/status_poster/status_poster.service.js'
import { useInstanceStore } from 'src/stores/instance.js'
import { useMergedConfigStore } from 'src/stores/merged_config.js'
import { isAnimated } from 'src/services/animated_image/animated_image.js'
import { library } from '@fortawesome/fontawesome-svg-core'
import { faCircleNotch, faUpload } from '@fortawesome/free-solid-svg-icons'
library.add(faUpload, faCircleNotch)
const mediaUpload = {
data() {
return {
uploadCount: 0,
uploadReady: true,
}
},
computed: {
uploading() {
return this.uploadCount > 0
},
},
methods: {
onClick() {
if (this.uploadReady) {
this.$refs.input.click()
}
},
async resizeImage(file) {
// Skip if not an image, a GIF or an SVG
if (
!file.type.startsWith('image/') ||
file.type === 'image/gif' ||
file.type === 'image/svg+xml'
) {
return file
}
// Skip if image compression is disabled
if (!useMergedConfigStore().mergedConfig.imageCompression) {
return file
}
// Animated pictures would lose their animation on the canvas
if (await isAnimated(file)) {
return file
}
return new Promise((resolve) => {
const img = new Image()
img.onload = () => {
// Calculate new dimensions
let width = img.width
let height = img.height
const maxSize = 2048
if (width > maxSize || height > maxSize) {
if (width > height) {
height = Math.round((height * maxSize) / width)
width = maxSize
} else {
width = Math.round((width * maxSize) / height)
height = maxSize
}
}
// Create canvas and resize
const canvas = document.createElement('canvas')
canvas.width = width
canvas.height = height
const ctx = canvas.getContext('2d')
ctx.drawImage(img, 0, 0, width, height)
// Check WebP support by trying to create a WebP canvas
const testCanvas = document.createElement('canvas')
const supportsWebP = testCanvas
.toDataURL('image/webp')
.startsWith('data:image/webp')
// Convert to WebP if supported and alwaysUseJpeg is false, otherwise JPEG
const type =
!useMergedConfigStore().mergedConfig.alwaysUseJpeg && supportsWebP
? 'image/webp'
: 'image/jpeg'
const extension = type === 'image/webp' ? '.webp' : '.jpg'
// Remove the original extension and add new one
const newFileName = file.name.replace(/\.[^/.]+$/, '') + extension
canvas.toBlob(
(blob) => {
+ // Keep the original if compressing did not make it smaller
+ if (blob.size >= file.size) {
+ resolve(file)
+ return
+ }
resolve(
new File([blob], newFileName, {
type,
lastModified: Date.now(),
}),
)
},
type,
0.85,
)
}
img.src = URL.createObjectURL(file)
})
},
async uploadFile(file) {
if (file.size > useInstanceStore().uploadlimit) {
const filesize = fileSizeFormatService.fileSizeFormat(file.size)
const allowedsize = fileSizeFormatService.fileSizeFormat(
useInstanceStore().uploadlimit,
)
this.$emit('upload-failed', 'file_too_big', {
filesize: filesize.num,
filesizeunit: filesize.unit,
allowedsize: allowedsize.num,
allowedsizeunit: allowedsize.unit,
})
return
}
// Resize image if needed
const processedFile = await this.resizeImage(file)
const formData = new FormData()
formData.append('file', processedFile)
this.$emit('uploading')
this.uploadCount++
statusPosterService.uploadMedia({ formData }).then(
(fileData) => {
this.$emit('uploaded', fileData)
this.decreaseUploadCount()
},
(error) => {
console.error('Error uploading file', error)
this.$emit('upload-failed', 'default')
this.decreaseUploadCount()
},
)
},
decreaseUploadCount() {
this.uploadCount--
if (this.uploadCount === 0) {
this.$emit('all-uploaded')
}
},
clearFile() {
this.uploadReady = false
this.$nextTick(() => {
this.uploadReady = true
})
},
multiUpload(files) {
for (const file of files) {
this.uploadFile(file)
}
},
change({ target }) {
this.multiUpload(target.files)
},
},
props: {
dropFiles: Object,
disabled: Boolean,
normalButton: Boolean,
acceptTypes: {
type: String,
default: '*/*',
},
},
watch: {
dropFiles: function (fileInfos) {
if (!this.uploading) {
this.multiUpload(fileInfos)
}
},
},
}
export default mediaUpload
diff --git a/test/fixtures/photo.js b/test/fixtures/photo.js
index 96d7a15aa5..4a047cb6b3 100644
--- a/test/fixtures/photo.js
+++ b/test/fixtures/photo.js
@@ -1,20 +1,33 @@
// A PNG that compresses well, like a photo: noise, which PNG keeps byte for
// byte and WebP or JPEG make much smaller. The same pixels every time.
export const photo = (width, height, name = 'photo.png') =>
new Promise((resolve) => {
const canvas = document.createElement('canvas')
canvas.width = width
canvas.height = height
const context = canvas.getContext('2d')
const pixels = context.createImageData(width, height)
let seed = 1
for (let i = 0; i < pixels.data.length; i++) {
seed = (seed * 1103515245 + 12345) & 0x7fffffff
pixels.data[i] = i % 4 === 3 ? 255 : seed >> 23
}
context.putImageData(pixels, 0, 0)
canvas.toBlob(
(blob) => resolve(new File([blob], name, { type: 'image/png' })),
'image/png',
)
})
+
+// A flat PNG, which PNG stores in fewer bytes than WebP or JPEG when small
+export const flat = (width, height, name = 'photo.png') =>
+ new Promise((resolve) => {
+ const canvas = document.createElement('canvas')
+ canvas.width = width
+ canvas.height = height
+ canvas.getContext('2d').fillRect(0, 0, width, height)
+ canvas.toBlob(
+ (blob) => resolve(new File([blob], name, { type: 'image/png' })),
+ 'image/png',
+ )
+ })
diff --git a/test/unit/specs/components/media_upload.spec.js b/test/unit/specs/components/media_upload.spec.js
index 5cd1c7dfca..e34a693d0c 100644
--- a/test/unit/specs/components/media_upload.spec.js
+++ b/test/unit/specs/components/media_upload.spec.js
@@ -1,32 +1,37 @@
import { createTestingPinia } from '@pinia/testing'
import { mount } from '@vue/test-utils'
import { setActivePinia } from 'pinia'
-import { photo } from 'test/fixtures/photo.js'
+import { flat, photo } from 'test/fixtures/photo.js'
import { mountOpts } from 'test/fixtures/setup_test.js'
import MediaUpload from 'src/components/media_upload/media_upload.vue'
import { useMergedConfigStore } from 'src/stores/merged_config.js'
const resize = (file) => {
setActivePinia(createTestingPinia())
useMergedConfigStore().mergedConfig = { imageCompression: true }
const wrapper = mount(MediaUpload, mountOpts())
return wrapper.vm.resizeImage(file)
}
describe('MediaUpload image compression', () => {
it('compresses a picture', async () => {
const out = await resize(await photo(100, 100))
expect(out.name).to.match(/^photo\.(webp|jpg)$/)
})
+ it('uploads the original when the compressed picture is not smaller', async () => {
+ const picture = await flat(4, 4)
+ expect(await resize(picture)).to.equal(picture)
+ })
+
it('does not rasterize SVG', async () => {
const svg = new File(
['<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"/>'],
'logo.svg',
{ type: 'image/svg+xml' },
)
expect(await resize(svg)).to.equal(svg)
})
})
File Metadata
Details
Attached
Mime Type
text/x-diff
Expires
Tue, Nov 17, 10:52 PM (18 h, 13 m)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
1839857
Default Alt Text
(8 KB)
Attached To
Mode
rPUFE pleroma-fe-upstream
Attached
Detach File
Event Timeline