From ef6d319545cb3b651c0e6b20ed93b014dcdf7658 Mon Sep 17 00:00:00 2001 From: fengxxc Date: Sun, 23 Oct 2022 00:52:11 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=96=87=E7=AB=A0=E4=B8=AD=E7=9A=84?= =?UTF-8?q?=E5=9B=BE=E7=89=87=E8=BD=AC=E6=88=90base64=E5=AD=98=E5=9C=A8?= =?UTF-8?q?=E7=94=9F=E6=88=90=E7=9A=84markdown=E9=87=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- format/format.go | 3 ++- parse/parse.go | 25 ++++++++++++++++++++++++- 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/format/format.go b/format/format.go index a87f31c..a41dc28 100644 --- a/format/format.go +++ b/format/format.go @@ -122,7 +122,8 @@ func formatCodeBlock(piece parse.Piece) string { } func formatImage(piece parse.Piece) string { - return "![" + piece.Attrs["alt"] + "](" + piece.Attrs["src"] + " \"" + piece.Attrs["title"] + "\")" + // return "![" + piece.Attrs["alt"] + "](" + piece.Attrs["src"] + " \"" + piece.Attrs["title"] + "\")" + return "![" + piece.Attrs["alt"] + "](data:image/png;base64," + piece.Val.(string) + ")" } func formatLink(piece parse.Piece) string { diff --git a/parse/parse.go b/parse/parse.go index 00f306d..d29ed70 100644 --- a/parse/parse.go +++ b/parse/parse.go @@ -2,6 +2,7 @@ package parse import ( "bytes" + "encoding/base64" "io" "io/ioutil" "log" @@ -25,7 +26,8 @@ func parseSection(s *goquery.Selection) []Piece { attr["src"], _ = sc.Attr("data-src") attr["alt"], _ = sc.Attr("alt") attr["title"], _ = sc.Attr("title") - pieces = append(pieces, Piece{IMAGE, "", attr}, Piece{BR, nil, nil}) + base64Image := img2base64(fetchImgFile(attr["src"])) + pieces = append(pieces, Piece{IMAGE, base64Image, attr}, Piece{BR, nil, nil}) } else if sc.Is("ol") { pieces = append(pieces, parseList(sc, O_LIST)...) } else if sc.Is("ul") { @@ -193,3 +195,24 @@ func removeBrAndBlank(s string) string { } return strings.Replace(string(sb), "\n", " ", -1) } + +func fetchImgFile(url string) []byte { + res, err := http.Get(url) + if err != nil { + log.Fatalf("get Image from url %s error: %s", url, err.Error()) + return nil + } + defer res.Body.Close() + if res.StatusCode != 200 { + log.Fatalf("get Image from url %s error: %d %s", url, res.StatusCode, res.Status) + } + content, err := ioutil.ReadAll(res.Body) + if err != nil { + log.Fatalf("read image Response error: %s", err.Error()) + } + return content +} + +func img2base64(content []byte) string { + return base64.StdEncoding.EncodeToString(content) +}