File size: 2,376 Bytes
edcf070
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aff35bf
edcf070
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6650d27
 
 
 
 
 
edcf070
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
package services

import (
	"bytes"
	"context"
	"fmt"
	"image"
	"image/jpeg"
	_ "image/png" // Support PNG decoding
	"io"
	"log"
	"mime/multipart"
	"service-warungpos-go/config"

	"github.com/cloudinary/cloudinary-go/v2"
	"github.com/cloudinary/cloudinary-go/v2/api/uploader"
)

// UploadToCloudinary mengompresi gambar dan mengunggahnya ke Cloudinary
func UploadToCloudinary(fileHeader *multipart.FileHeader) (string, error) {
	// Buka file dari fileHeader
	file, err := fileHeader.Open()
	if err != nil {
		return "", fmt.Errorf("gagal membuka file: %v", err)
	}
	defer file.Close()

	// Baca seluruh bytes file
	contents, err := io.ReadAll(file)
	if err != nil {
		return "", fmt.Errorf("gagal membaca file: %v", err)
	}

	// Kompresi gambar ke JPEG dengan quality 75
	compressedBytes, err := compressImage(contents)
	if err != nil {
		log.Printf("[CLOUDINARY] Gagal kompresi, menggunakan file asli: %v", err)
		compressedBytes = contents
	}

	// Inisialisasi Cloudinary dari parameter config
	cld, err := cloudinary.NewFromParams(
		config.GlobalConfig.CloudinaryCloudName,
		config.GlobalConfig.CloudinaryAPIKey,
		config.GlobalConfig.CloudinaryAPISecret,
	)
	if err != nil {
		return "", fmt.Errorf("gagal inisialisasi Cloudinary: %v", err)
	}

	ctx := context.Background()

	// Gunakan Reader dari compressedBytes untuk upload
	resp, err := cld.Upload.Upload(ctx, bytes.NewReader(compressedBytes), uploader.UploadParams{
		Folder: "warungpos/products",
	})
	if err != nil {
		return "", fmt.Errorf("gagal upload ke Cloudinary: %v", err)
	}

	// Cloudinary SDK does not return an error when credentials or cloud name are invalid,
	// instead it populates the Error field in the response. We must check it!
	if resp.Error.Message != "" {
		return "", fmt.Errorf("cloudinary error: %s", resp.Error.Message)
	}

	log.Printf("[CLOUDINARY] Upload sukses! URL: %s", resp.SecureURL)
	return resp.SecureURL, nil
}

// compressImage mengompresi gambar ke JPEG (kualitas 75)
func compressImage(imgBytes []byte) ([]byte, error) {
	// Decode gambar (mendukung JPEG/PNG/WebP jika didaftarkan)
	img, _, err := image.Decode(bytes.NewReader(imgBytes))
	if err != nil {
		return nil, err
	}

	// Encode ulang sebagai JPEG dengan kualitas 75
	var buf bytes.Buffer
	err = jpeg.Encode(&buf, img, &jpeg.Options{Quality: 75})
	if err != nil {
		return nil, err
	}

	return buf.Bytes(), nil
}