[htmlgrab] Added support for base64 images

This commit is contained in:
Pijus Kamandulis
2021-06-09 19:07:07 +03:00
parent 01f7879f7e
commit 38f9cdeb09
5 changed files with 95 additions and 14 deletions

View File

@@ -7,18 +7,18 @@ import (
)
// DownloadFile - Download file and store it
func DownloadFile(outputFilename string, url string) {
func DownloadFile(outputFilename string, url string) error {
// Get the data
resp, err := http.Get(url)
if err != nil {
panic(err)
return err
}
defer resp.Body.Close()
// Create the file
out, err := os.Create(outputFilename)
if err != nil {
panic(err)
return err
}
defer out.Close()
@@ -26,6 +26,8 @@ func DownloadFile(outputFilename string, url string) {
_, err = io.Copy(out, resp.Body)
if err != nil {
panic(err)
return err
}
return nil
}

48
fileio/saveFromBase64.go Normal file
View File

@@ -0,0 +1,48 @@
package fileio
import (
"bytes"
"encoding/base64"
"fmt"
"image/jpeg"
"image/png"
"os"
"strings"
crypto "github.com/pikami/rss-dl/crypto"
)
func SaveFromBase64(imgStr string, basePath string) string {
sha1 := crypto.ShaStr(imgStr)
coI := strings.Index(string(imgStr), ",")
rawImage := string(imgStr)[coI+1:]
// Encoded Image DataUrl //
unbased, _ := base64.StdEncoding.DecodeString(string(rawImage))
res := bytes.NewReader(unbased)
switch strings.TrimSuffix(imgStr[5:coI], ";base64") {
case "image/png":
pngI, err := png.Decode(res)
if err == nil {
fileSavePath := basePath + "/" + sha1 + ".png"
f, _ := os.OpenFile(fileSavePath, os.O_WRONLY|os.O_CREATE, 0777)
png.Encode(f, pngI)
fmt.Println("[save base64] Created image: " + fileSavePath)
f.Close()
}
return sha1 + ".png"
case "image/jpeg":
jpgI, err := jpeg.Decode(res)
if err == nil {
fileSavePath := basePath + "/" + sha1 + ".jpg"
f, _ := os.OpenFile(fileSavePath, os.O_WRONLY|os.O_CREATE, 0777)
jpeg.Encode(f, jpgI, &jpeg.Options{Quality: 100})
fmt.Println("[save base64] Created image: " + fileSavePath)
f.Close()
}
return sha1 + ".jpg"
}
return "#"
}