Skip to content

Commit

Permalink
Merge pull request #31 from isd-sgcu/compress-image
Browse files Browse the repository at this point in the history
compress image
  • Loading branch information
bookpanda authored Jul 18, 2024
2 parents 401ad43 + 67387c2 commit 384634f
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 13 deletions.
1 change: 1 addition & 0 deletions docker-compose.qa.template.yml
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@ services:
STORE_ENDPOINT: endpoint
STORE_ACCESS_KEY: access_key
STORE_SECRET_KEY: secret_key
STORE_REGION: ap-southeast-1
STORE_USE_SSL: true
STORE_BUCKET_NAME: rpkm67-local
networks:
Expand Down
55 changes: 42 additions & 13 deletions internal/context/context.utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ import (
"bytes"
"errors"
"fmt"
"io"
"image"
"image/jpeg"
"mime/multipart"
"strings"
)
Expand All @@ -14,23 +15,15 @@ func ExtractFile(file *multipart.FileHeader, allowedContent map[string]struct{},
return nil, errors.New("Allowed content type is " + fmt.Sprint(strings.Join(mapToArr(allowedContent), ", ")))
}

if file.Size > maxSize*1000000000 {
return nil, fmt.Errorf("max file size is %v", maxSize)
}

fileBytes, err := file.Open()
maxSizeMB := maxSize * 1024 * 1024
fileBytes, err := compressImage(file, int(maxSizeMB))
if err != nil {
return nil, err
}

defer fileBytes.Close()

buf := bytes.NewBuffer(nil)
if _, err := io.Copy(buf, fileBytes); err != nil {
return nil, err
}
println("File size: ", len(fileBytes))

return buf.Bytes(), nil
return fileBytes, nil
}

func isExisted(e map[string]struct{}, key string) bool {
Expand All @@ -45,3 +38,39 @@ func mapToArr(m map[string]struct{}) []string {
}
return arr
}

func compressImage(fileHeader *multipart.FileHeader, maxSizeMB int) ([]byte, error) {
file, err := fileHeader.Open()
if err != nil {
return nil, err
}
defer file.Close()

img, _, err := image.Decode(file)
if err != nil {
return nil, err
}

var quality int = 80
var compressed []byte

for {
buf := new(bytes.Buffer)
if err := jpeg.Encode(buf, img, &jpeg.Options{Quality: quality}); err != nil {
return nil, err
}
compressed = buf.Bytes()

if len(compressed) <= maxSizeMB {
break
}

// Reduce quality if size is still too large
quality -= 10
if quality <= 0 {
return nil, fmt.Errorf(fmt.Sprintf("unable to compress image to %v MB", maxSizeMB/(1024*1024)))
}
}

return compressed, nil
}

0 comments on commit 384634f

Please sign in to comment.