Page MenuHomePhorge

No OneTemporary

Authored By
Unknown
Size
8 KB
Referenced Files
None
Subscribers
None
diff --git a/changelog.d/svg-upload.fix b/changelog.d/svg-upload.fix
new file mode 100644
index 0000000000..e69fc5cc47
--- /dev/null
+++ b/changelog.d/svg-upload.fix
@@ -0,0 +1 @@
+SVG pictures are uploaded as they are, not turned into WebP or JPEG
diff --git a/src/components/media_upload/media_upload.js b/src/components/media_upload/media_upload.js
index bf29cf6d0c..cead5b9951 100644
--- a/src/components/media_upload/media_upload.js
+++ b/src/components/media_upload/media_upload.js
@@ -1,179 +1,183 @@
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 or if it's a GIF
- if (!file.type.startsWith('image/') || file.type === 'image/gif') {
+ // 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) => {
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
new file mode 100644
index 0000000000..96d7a15aa5
--- /dev/null
+++ b/test/fixtures/photo.js
@@ -0,0 +1,20 @@
+// 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',
+ )
+ })
diff --git a/test/unit/specs/components/media_upload.spec.js b/test/unit/specs/components/media_upload.spec.js
new file mode 100644
index 0000000000..5cd1c7dfca
--- /dev/null
+++ b/test/unit/specs/components/media_upload.spec.js
@@ -0,0 +1,32 @@
+import { createTestingPinia } from '@pinia/testing'
+import { mount } from '@vue/test-utils'
+import { setActivePinia } from 'pinia'
+import { 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('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

Mime Type
text/x-diff
Expires
Tue, Nov 17, 10:06 AM (4 h, 17 m)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
1839452
Default Alt Text
(8 KB)

Event Timeline