personal-website/fileuploading/fileuploading.go

106 lines
2.4 KiB
Go
Raw Normal View History

2023-05-01 12:32:41 +00:00
package fileuploading
//sudo apt-get install libvips-tools
import (
"encoding/base64"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"path"
"personalwebsite/wde"
"personalwebsite/webfilesystem"
"strings"
"github.com/disintegration/imaging"
"go.mongodb.org/mongo-driver/bson/primitive"
)
type FileUploading struct {
fs *webfilesystem.WebFileSystem
}
func NewFileUploading(webfs *webfilesystem.WebFileSystem) *FileUploading {
return &FileUploading{
fs: webfs,
}
}
func (f *FileUploading) CreateMiniatures(parentDir string, file string) error {
src, err := imaging.Open(path.Join(parentDir, file))
if err != nil {
// log.Fatalf("failed to open image: %v", err)
return err
}
// Resize the cropped image to width = 200px preserving the aspect ratio.
src = imaging.Resize(src, 32, 0, imaging.Lanczos)
// Save the resulting image as JPEG.
splittedFileName := strings.Split(file, ".")
err = imaging.Save(src, path.Join(parentDir, splittedFileName[0]+"_32px."+splittedFileName[1]))
if err != nil {
// log.Fatalf("failed to save image: %v", err)
return err
}
data, err := os.ReadFile(path.Join(parentDir, file))
if err != nil {
return err
}
min32Data, err := os.ReadFile(path.Join(parentDir, splittedFileName[0]+"_32px."+splittedFileName[1]))
if err != nil {
return err
}
imgData := wde.Img{
Header: "",
Data: data,
Miniature32: min32Data,
}
newFile := webfilesystem.WebFSFile{
MongoId: primitive.NewObjectID(),
Name: file,
Type: "picture",
Data: imgData,
Icon: "",
}
f.fs.CreateFile(&newFile, "/home/user/")
return nil
}
func (f *FileUploading) EncodeToBase64(path string) (string, string) {
// Read the entire file into a byte slice
bytes, err := ioutil.ReadFile(path)
if err != nil {
log.Fatal(err)
}
var base64Encoding string
// Determine the content type of the image file
mimeType := http.DetectContentType(bytes)
// Prepend the appropriate URI scheme header depending
// on the MIME type
switch mimeType {
case "image/jpeg":
base64Encoding += "image/jpeg;base64"
case "image/png":
base64Encoding += "image/png;base64"
}
// Append the base64 encoded output
// base64Encoding += toBase64(bytes)
// Print the full base64 representation of the image
fmt.Println(base64Encoding)
return base64Encoding, toBase64(bytes)
}
func toBase64(b []byte) string {
return base64.StdEncoding.EncodeToString(b)
}