-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathutil.go
62 lines (54 loc) · 1.76 KB
/
util.go
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
// Copyright (C) 2020 David Vogel
//
// This file is part of Galago.
//
// Galago is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 2 of the License, or
// (at your option) any later version.
//
// Galago is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Galago. If not, see <http://www.gnu.org/licenses/>.
package main
import (
"encoding/base64"
"fmt"
"io/ioutil"
"strings"
)
// ExtToMIME returns the MIME media type of a given file extension.
// Example: ".jpg" returns "image/jpeg".
func ExtToMIME(ext string) string {
switch strings.ToLower(ext) {
case ".jpg", ".jpeg":
return "image/jpeg"
case ".png":
return "image/png"
case ".bmp":
return "image/bmp"
}
return "application/octet-stream"
}
// ImageToDataURI takes the result from FileContent and returns an data URI that can be embedded into HTML or CSS.
// This will close the stream f.
func ImageToDataURI(img Image) (string, error) {
ce, err := img.CacheEntry()
if err != nil {
return "", fmt.Errorf("Couldn't find cache entry for %v: %w", img, err)
}
f, _, mime, err := ce.NanoImage()
if err != nil {
return "", fmt.Errorf("Couldn't get file of image %v: %w", img, err)
}
defer f.Close()
buf, err := ioutil.ReadAll(f)
if err != nil {
return "", fmt.Errorf("Couldn't read file content of image %v: %w", img, err)
}
return fmt.Sprintf("data:%v;base64,%v", mime, base64.StdEncoding.EncodeToString(buf)), nil
}