Skip to content

Commit

Permalink
chroe: base64 data
Browse files Browse the repository at this point in the history
  • Loading branch information
wenlng committed Nov 15, 2024
1 parent 8ad0fdf commit 4fe0ef2
Show file tree
Hide file tree
Showing 20 changed files with 207 additions and 115 deletions.
17 changes: 10 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -438,17 +438,20 @@ builder.SetResources(rotate.WithXxx(), ...)
## Captcha Image Data
### JPEGImageData object method
- Get() image.Image
- ToBytes() []byte
- ToBytesWithQuality(imageQuality int) []byte
- ToBase64() string
- ToBase64WithQuality(imageQuality int) string
- ToBytes() ([]byte, error)
- ToBytesWithQuality(imageQuality int) ([]byte, error)
- ToBase64() (string, error)
- ToBase64Data() (string, error)
- ToBase64WithQuality(imageQuality int) (string, error)
- ToBase64DataWithQuality(imageQuality int) (string, error)
- SaveToFile(filepath string, quality int) error


### PNGImageData object method
- Get() image.Image
- ToBytes() []byte
- ToBase64() string
- ToBytes() ([]byte, error)
- ToBase64() (string, error)
- ToBase64Data() (string, error)
- SaveToFile(filepath string) error

<br/>
Expand All @@ -462,9 +465,9 @@ builder.SetResources(rotate.WithXxx(), ...)
- <p>Solid ✔</p>
- <p>MinProgram</p>
- <p>UniApp</p>
- <p>Flutter App</p>
- <p>Android App</p>
- <p>IOS App</p>
- <p>Flutter App</p>
- <p>... </p>

<br/>
Expand Down
15 changes: 9 additions & 6 deletions README_zh.md
Original file line number Diff line number Diff line change
Expand Up @@ -455,17 +455,20 @@ func loadPng(p string) (image.Image, error) {

### JPEGImageData
- Get() image.Image 获取原图像
- ToBytes() []byte 转为JPEG字节数组
- ToBytesWithQuality(imageQuality int) []byte 指定清晰度转为JPEG字节数组
- ToBase64() string 转为 JPEG Base64 字符串
- ToBase64WithQuality(imageQuality int) string 指定清晰度转为 JPEG Base64 字符串
- ToBytes() ([]byte, error) 转为JPEG字节数组
- ToBytesWithQuality(imageQuality int) ([]byte, error) 指定清晰度转为JPEG字节数组
- ToBase64() (string, error) 转为 JPEG Base64 字符串
- ToBase64Data() (string, error) 转为 JPEG Base64 字符串,带 "data:image/jpeg;base64," 前缀
- ToBase64WithQuality(imageQuality int) (string, error) 指定清晰度转为 JPEG Base64 字符串
- ToBase64DataWithQuality(imageQuality int) (string, error) 指定清晰度转为 JPEG Base64 字符串,带 "data:image/jpeg;base64," 前缀
- SaveToFile(filepath string, quality int) error 保存 JPEG 到文件


### PNGImageData
- Get() image.Image 获取原图像
- ToBytes() []byte 转为PNG字节数组
- ToBase64() string 转为 PNG Base64 字符串
- ToBytes() ([]byte, error) 转为PNG字节数组
- ToBase64() (string, error) 转为 PNG Base64 字符串
- ToBase64Data() (string, error) 转为 PNG Base64 字符串,带 "data:image/png;base64," 前缀
- SaveToFile(filepath string) error 保存 PNG 到文件

<br/>
Expand Down
5 changes: 2 additions & 3 deletions v2/base/canvas/canvas.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,8 @@ import (

// CreatePaletteCanvas is to the canvas that creates the palette
func CreatePaletteCanvas(width, height int, colour []color.RGBA) Palette {
p := []color.Color{
color.RGBA{R: 0xFF, G: 0xFF, B: 0xFF, A: 0x00},
}
p := make([]color.Color, 0, len(colour)+1)
p = append(p, color.RGBA{R: 0xFF, G: 0xFF, B: 0xFF, A: 0x00})

for _, co := range colour {
p = append(p, co)
Expand Down
5 changes: 1 addition & 4 deletions v2/base/canvas/nrgba.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
package canvas

import (
"fmt"
"image"
"image/color"
"math"
Expand Down Expand Up @@ -75,9 +74,7 @@ func (n *nRGBA) DrawString(params *DrawStringParams, pt fixed.Point26_6) error {
fontColor := image.NewUniform(params.Color)
dc.SetSrc(fontColor)

text := fmt.Sprintf("%s", params.Text)

if _, err := dc.DrawString(text, pt); err != nil {
if _, err := dc.DrawString(params.Text, pt); err != nil {
return err
}

Expand Down
5 changes: 1 addition & 4 deletions v2/base/canvas/palette.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
package canvas

import (
"fmt"
"image"
"image/color"
"math"
Expand Down Expand Up @@ -239,9 +238,7 @@ func (p *palette) DrawString(params *DrawStringParams, pt fixed.Point26_6) error
fontColor := image.NewUniform(params.Color)
dc.SetSrc(fontColor)

text := fmt.Sprintf("%s", params.Text)

if _, err := dc.DrawString(text, pt); err != nil {
if _, err := dc.DrawString(params.Text, pt); err != nil {
return err
}

Expand Down
53 changes: 42 additions & 11 deletions v2/base/codec/codec.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,28 +9,30 @@ package codec
import (
"bytes"
"encoding/base64"
"fmt"
"image"
"image/jpeg"
"image/png"
)

const pngBasePrefix = "data:image/png;base64,"
const jpegBasePrefix = "data:image/jpeg;base64,"

// EncodePNGToByte is to encode the png into a byte array
func EncodePNGToByte(img image.Image) (ret []byte) {
func EncodePNGToByte(img image.Image) (ret []byte, err error) {
var buf bytes.Buffer
if err := png.Encode(&buf, img); err != nil {
panic(err.Error())
if err = png.Encode(&buf, img); err != nil {
return
}
ret = buf.Bytes()
buf.Reset()
return
}

// EncodeJPEGToByte is to encode the image into a byte array
func EncodeJPEGToByte(img image.Image, quality int) (ret []byte) {
func EncodeJPEGToByte(img image.Image, quality int) (ret []byte, err error) {
var buf bytes.Buffer
if err := jpeg.Encode(&buf, img, &jpeg.Options{Quality: quality}); err != nil {
panic(err.Error())
if err = jpeg.Encode(&buf, img, &jpeg.Options{Quality: quality}); err != nil {
return
}
ret = buf.Bytes()
buf.Reset()
Expand All @@ -55,12 +57,41 @@ func DecodeByteToPng(b []byte) (img image.Image, err error) {
return
}

// EncodePNGToBase64Data is to encode the png into string
func EncodePNGToBase64Data(img image.Image) (string, error) {
base64Str, err := EncodePNGToBase64(img)
if err != nil {
return "", err
}

return pngBasePrefix + base64Str, nil
}

// EncodeJPEGToBase64Data is to encode the image into string
func EncodeJPEGToBase64Data(img image.Image, quality int) (string, error) {
base64Str, err := EncodeJPEGToBase64(img, quality)
if err != nil {
return "", err
}

return jpegBasePrefix + base64Str, nil
}

// EncodePNGToBase64 is to encode the png into string
func EncodePNGToBase64(img image.Image) string {
return fmt.Sprintf("data:%s;base64,%s", "image/png", base64.StdEncoding.EncodeToString(EncodePNGToByte(img)))
func EncodePNGToBase64(img image.Image) (string, error) {
byteCode, err := EncodePNGToByte(img)
if err != nil {
return "", err
}
return base64.StdEncoding.EncodeToString(byteCode), nil
}

// EncodeJPEGToBase64 is to encode the image into string
func EncodeJPEGToBase64(img image.Image, quality int) string {
return fmt.Sprintf("data:%s;base64,%s", "image/jpeg", base64.StdEncoding.EncodeToString(EncodeJPEGToByte(img, quality)))
func EncodeJPEGToBase64(img image.Image, quality int) (string, error) {
byteCode, err := EncodeJPEGToByte(img, quality)
if err != nil {
return "", err
}

return base64.StdEncoding.EncodeToString(byteCode), nil
}
14 changes: 8 additions & 6 deletions v2/base/helper/helper.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import (
"image/color"
"math"
"os"
"regexp"
"strconv"
"unicode"
"unicode/utf8"
Expand All @@ -28,7 +27,7 @@ func t2x(t int64) string {
return result
}

// FormatAlpha is to formatting transparent
// FormatAlpha is formatting transparent
func FormatAlpha(val float32) uint8 {
a := math.Min(float64(val), 1)
alpha := a * 255
Expand All @@ -51,11 +50,14 @@ func HexToRgb(hex string) (int64, int64, int64) {
return r, g, b
}

var ColorHexFormatErr = errors.New("hex color must start with '#'")
var ColorInvalidErr = errors.New("hexToByte component invalid")

// ParseHexColor is to turn the hex color to RGB color
func ParseHexColor(s string) (c color.RGBA, err error) {
c.A = 0xff
if s[0] != '#' {
return c, errors.New("hex color must start with '#'")
return c, ColorHexFormatErr
}

hexToByte := func(b byte) byte {
Expand All @@ -67,7 +69,7 @@ func ParseHexColor(s string) (c color.RGBA, err error) {
case b >= 'A' && b <= 'F':
return b - 'A' + 10
}
err = errors.New("hexToByte component invalid")
err = ColorInvalidErr
return 0
}

Expand All @@ -82,7 +84,7 @@ func ParseHexColor(s string) (c color.RGBA, err error) {
c.G = hexToByte(s[2]) * 17
c.B = hexToByte(s[3]) * 17
default:
err = errors.New("hexToByte component invalid")
err = ColorInvalidErr
}
return
}
Expand Down Expand Up @@ -112,7 +114,7 @@ func InArrayWithStr(items []string, s string) bool {
// IsChineseChar is to detect whether it is Chinese
func IsChineseChar(str string) bool {
for _, r := range str {
if unicode.Is(unicode.Scripts["Han"], r) || (regexp.MustCompile("[\u3002\uff1b\uff0c\uff1a\u201c\u201d\uff08\uff09\u3001\uff1f\u300a\u300b]").MatchString(string(r))) {
if unicode.Is(unicode.Scripts["Han"], r) {
return true
}
}
Expand Down
4 changes: 4 additions & 0 deletions v2/base/imagedata/base.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,17 @@
package imagedata

import (
"errors"
"image"
"image/jpeg"
"image/png"
"os"
"path"
)

var ImageEmptyErr = errors.New("image is empty")
var ImageMissingDataErr = errors.New("missing image data")

// saveToFile .
func saveToFile(img image.Image, filepath string, isTransparent bool, quality int) error {
var file *os.File
Expand Down
50 changes: 36 additions & 14 deletions v2/base/imagedata/jpegdata.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
package imagedata

import (
"fmt"
"image"

"github.com/wenlng/go-captcha/v2/base/codec"
Expand All @@ -17,10 +16,12 @@ import (
// JPEGImageData .
type JPEGImageData interface {
Get() image.Image
ToBytes() []byte
ToBytesWithQuality(imageQuality int) []byte
ToBase64() string
ToBase64WithQuality(imageQuality int) string
ToBytes() ([]byte, error)
ToBytesWithQuality(imageQuality int) ([]byte, error)
ToBase64() (string, error)
ToBase64WithQuality(imageQuality int) (string, error)
ToBase64Data() (string, error)
ToBase64DataWithQuality(imageQuality int) (string, error)
SaveToFile(filepath string, quality int) error
}

Expand All @@ -46,25 +47,25 @@ func (c *jpegImageDta) Get() image.Image {
// SaveToFile is to save JPEG as a file
func (c *jpegImageDta) SaveToFile(filepath string, quality int) error {
if c.image == nil {
return fmt.Errorf("missing image data")
return ImageMissingDataErr
}

return saveToFile(c.image, filepath, false, quality)
}

// ToBytes is to convert JPEG into byte array
func (c *jpegImageDta) ToBytes() []byte {
func (c *jpegImageDta) ToBytes() ([]byte, error) {
if c.image == nil {
return []byte{}
return []byte{}, ImageEmptyErr
}

return codec.EncodeJPEGToByte(c.image, option.QualityNone)
}

// ToBytesWithQuality is to convert JPEG into byte array with quality
func (c *jpegImageDta) ToBytesWithQuality(imageQuality int) []byte {
func (c *jpegImageDta) ToBytesWithQuality(imageQuality int) ([]byte, error) {
if c.image == nil {
return []byte{}
return []byte{}, ImageEmptyErr
}

if imageQuality <= option.QualityNone && imageQuality >= option.QualityLevel5 {
Expand All @@ -73,19 +74,40 @@ func (c *jpegImageDta) ToBytesWithQuality(imageQuality int) []byte {
return codec.EncodeJPEGToByte(c.image, option.QualityNone)
}

// ToBase64Data is to convert JPEG into base64
func (c *jpegImageDta) ToBase64Data() (string, error) {
if c.image == nil {
return "", ImageEmptyErr
}

return codec.EncodeJPEGToBase64Data(c.image, option.QualityNone)
}

// ToBase64DataWithQuality is to convert JPEG into base64 with quality
func (c *jpegImageDta) ToBase64DataWithQuality(imageQuality int) (string, error) {
if c.image == nil {
return "", ImageEmptyErr
}

if imageQuality <= option.QualityNone && imageQuality >= option.QualityLevel5 {
return codec.EncodeJPEGToBase64Data(c.image, imageQuality)
}
return codec.EncodeJPEGToBase64Data(c.image, option.QualityNone)
}

// ToBase64 is to convert JPEG into base64
func (c *jpegImageDta) ToBase64() string {
func (c *jpegImageDta) ToBase64() (string, error) {
if c.image == nil {
return ""
return "", ImageEmptyErr
}

return codec.EncodeJPEGToBase64(c.image, option.QualityNone)
}

// ToBase64WithQuality is to convert JPEG into base64 with quality
func (c *jpegImageDta) ToBase64WithQuality(imageQuality int) string {
func (c *jpegImageDta) ToBase64WithQuality(imageQuality int) (string, error) {
if c.image == nil {
return ""
return "", ImageEmptyErr
}

if imageQuality <= option.QualityNone && imageQuality >= option.QualityLevel5 {
Expand Down
Loading

0 comments on commit 4fe0ef2

Please sign in to comment.