使用Base64 GoLang模板显示图像

huangapple go评论79阅读模式
英文:

Display Image using Base64 GoLang Template

问题

我正在尝试在GoLang中使用Base64显示图像。我查看了各种示例,无论在哪里,都是相同的模式。这是我的代码:

{{template "base" .}}

{{define "content"}}
    {{$item := index .Data "item"}}
    {{$image := index .Data "image"}}
    
    <img src="data:image/png;base64," + {{$image.ImageDataBase64}} alt="Blank"/>
    {{$image.ImageDataBase64}}
{{end}}

请注意,我首先尝试使用base64显示图像,然后打印base64以确保一切正常。这是我得到的结果:

所以,它实际上显示了base64,但是当我将base64插入到<img/>标签中时,它不显示图像。为什么?

这是我创建base64的方式:

package images

import (
	"bytes"
	"encoding/base64"
	"fmt"
	"image/jpeg"
	"image/png"
	"io/ioutil"
	"log"
	"net/http"
)

var TmpDirectory string // Temorary Directory where all images in current session wil be stored

func setupCorsResponse(w *http.ResponseWriter, r *http.Request) {
	(*w).Header().Set("Access-Control-Allow-Origin", "*")
	(*w).Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
	(*w).Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Authorization")
}

func HandleUpload(w http.ResponseWriter, r *http.Request, formFileName string) (string, string, error) {
	// Maximum upload of 10 MB files r.ParseMultipartForm(1 << 2)

	file, handler, err := r.FormFile(formFileName)
	if err != nil {
		// If there is an error that means form is empty. Return nil for err in order
		// to validate result as required.
		return "", "", nil
	}

	defer file.Close()

	fmt.Printf("Uploaded File: %+v\n", handler.Filename)
	fmt.Printf("File Size: %+v\n", handler.Size)
	fmt.Printf("MIME Header: %+v\n", handler.Header)

	data, err := ioutil.ReadAll(file)
	if err != nil {
		log.Println(err)
		return "", "", err
	}

	contentType := http.DetectContentType(data)

	switch contentType {
	case "image/png":
		fmt.Println("Image type is already PNG.")
	case "image/jpeg":
		fmt.Println("Image type is JPG, converting it to PNG.")
		img, err := jpeg.Decode(bytes.NewReader(data))
		if err != nil {
			return "", "", fmt.Errorf("unable to decode jpeg: %w", err)
		}
		var buf bytes.Buffer

		if err := png.Encode(&buf, img); err != nil {
			return "", "", fmt.Errorf("unable to encode png")
		}
		data = buf.Bytes()
	default:
		return "", "", fmt.Errorf("unsupported content type: %s", contentType)
	}
	//convert the buffer bytes to base64 string - use buf.Bytes() for new image
	imgBase64Str := base64.StdEncoding.EncodeToString(data)
	return handler.Filename, imgBase64Str, nil
}

我在这里做错了什么?

英文:

I am trying to display image using Base 64 in GoLang. I've looked at various examples and everywhere its the same pattern. Here is my code:

{{template &quot;base&quot; .}}
{{define &quot;content&quot;}}
{{$item := index .Data &quot;item&quot;}}
{{$image := index .Data &quot;image&quot;}}
&lt;img src=&quot;data:image/png;base64,&quot; + {{$image.ImageDataBase64}} alt=&quot;Blank&quot;/&gt;
{{$image.ImageDataBase64}}
{{end}}

Note that I am first trying to show image using base64, and then I am printing base64 just to make sure everything is okay. And here is the result I am getting:
使用Base64 GoLang模板显示图像

So, it actually displays base64, but it does not display the image when I insert base64 in <img/> tag. Why?

Here is how I created base64:

package images
import (
&quot;bytes&quot;
&quot;encoding/base64&quot;
&quot;fmt&quot;
&quot;image/jpeg&quot;
&quot;image/png&quot;
&quot;io/ioutil&quot;
&quot;log&quot;
&quot;net/http&quot;
)
var TmpDirectory string // Temorary Directory where all images in current session wil be stored
func setupCorsResponse(w *http.ResponseWriter, r *http.Request) {
(*w).Header().Set(&quot;Access-Control-Allow-Origin&quot;, &quot;*&quot;)
(*w).Header().Set(&quot;Access-Control-Allow-Methods&quot;, &quot;POST, GET, OPTIONS, PUT, DELETE&quot;)
(*w).Header().Set(&quot;Access-Control-Allow-Headers&quot;, &quot;Accept, Content-Type, Content-Length, Authorization&quot;)
}
func HandleUpload(w http.ResponseWriter, r *http.Request, formFileName string) (string, string, error) {
// Maximum upload of 10 MB files r.ParseMultipartForm(1 &lt;&lt; 2)
file, handler, err := r.FormFile(formFileName)
if err != nil {
// If there is an error that means form is empty. Return nil for err in order
// to validate result as required.
return &quot;&quot;, &quot;&quot;, nil
}
defer file.Close()
fmt.Printf(&quot;Uploaded File: %+v\n&quot;, handler.Filename)
fmt.Printf(&quot;File Size: %+v\n&quot;, handler.Size)
fmt.Printf(&quot;MIME Header: %+v\n&quot;, handler.Header)
data, err := ioutil.ReadAll(file)
if err != nil {
log.Println(err)
return &quot;&quot;, &quot;&quot;, err
}
contentType := http.DetectContentType(data)
switch contentType {
case &quot;image/png&quot;:
fmt.Println(&quot;Image type is already PNG.&quot;)
case &quot;image/jpeg&quot;:
fmt.Println(&quot;Image type is JPG, converting it to PNG.&quot;)
img, err := jpeg.Decode(bytes.NewReader(data))
if err != nil {
return &quot;&quot;, &quot;&quot;, fmt.Errorf(&quot;unable to decode jpeg: %w&quot;, err)
}
var buf bytes.Buffer
if err := png.Encode(&amp;buf, img); err != nil {
return &quot;&quot;, &quot;&quot;, fmt.Errorf(&quot;unable to encode png&quot;)
}
data = buf.Bytes()
default:
return &quot;&quot;, &quot;&quot;, fmt.Errorf(&quot;unsupported content type: %s&quot;, contentType)
}
//convert the buffer bytes to base64 string - use buf.Bytes() for new image
imgBase64Str := base64.StdEncoding.EncodeToString(data)
return handler.Filename, imgBase64Str, nil
}

What am I doing wrong here?

答案1

得分: 1

"Blank"显示是因为您失败的图像的alt文本为"Blank"。

<img src="data:image/png;base64,{{$image.ImageDataBase64}}" alt="Blank"/>

给定值"AAAA",您从模板中得到的输出将是:

<img src="data:image/png;base64,AAAA" alt="Blank"/>

您可能需要进行简单的更改:

<img src="data:image/png;base64,{{$image.ImageDataBase64}}" alt="Blank"/>

这将产生:

<img src="data:image/png;base64,AAAA" alt="Blank"/>

请记住,您不是在构建字符串(或使用+运算符进行连接),而是只输出字符串的内容。

英文:

Blank is showing because your alt text for your failing image is Blank.

&lt;img src=&quot;data:image/png;base64,&quot; + {{$image.ImageDataBase64}} alt=&quot;Blank&quot;/&gt;

Given a value of "AAAA" your output from the template would be

&lt;img src=&quot;data:image/png;base64,&quot; + AAAA alt=&quot;Blank&quot;/&gt;

What you likely want requires a simple change:

&lt;img src=&quot;data:image/png;base64,{{$image.ImageDataBase64}}&quot; alt=&quot;Blank&quot;/&gt;

Which would produce

&lt;img src=&quot;data:image/png;base64,AAAA&quot; alt=&quot;Blank&quot;/&gt;

Remember, you aren't building a string (or concatenating with + operator) you are just output the contents of the string.

huangapple
  • 本文由 发表于 2021年9月14日 06:00:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/69169564.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定