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) +}