Code Monkey home page Code Monkey logo

Comments (2)

disintegration avatar disintegration commented on July 20, 2024

Hi,

You're using bufio.Writer, so you need to flush the buffer after writing an image:

func (s SpriteImage) GetBytes() ([]byte, error) {
    var b bytes.Buffer
    w := bufio.NewWriter(&b)

    if s.sprite == nil {
        return nil, fmt.Errorf("sprite is nil")
    }

    if err := imaging.Encode(w, s.sprite, imaging.JPEG); err != nil {
        return nil, err
    }

    if err := w.Flush(); err != nil {
        return nil, err
    }

    return b.Bytes(), nil
}

I believe you don't actually need a buffered writer if you're writing to bytes.Buffer:

func (s SpriteImage) GetBytes() ([]byte, error) {
    var b bytes.Buffer

    if s.sprite == nil {
        return nil, fmt.Errorf("sprite is nil")
    }

    if err := imaging.Encode(&b, s.sprite, imaging.JPEG); err != nil {
        return nil, err
    }

    return b.Bytes(), nil
}

The native JPEG Encode function takes up an image, but I have an image.NRGBA.

*image.NRGBA implements image.Image interface, so you can use jpeg.Encode directly if you want:

func (s SpriteImage) GetBytes() ([]byte, error) {
    var b bytes.Buffer

    if s.sprite == nil {
        return nil, fmt.Errorf("sprite is nil")
    }

    if err := jpeg.Encode(&b, s.sprite, nil); err != nil {
        return nil, err
    }

    return b.Bytes(), nil
}

I've made a small program from your snippets and it works for me:

package main

import (
    "bufio"
    "bytes"
    "fmt"
    "image"
    "image/color"
    "log"
    "os"

    "github.com/disintegration/imaging"
)

func main() {
    const size = 50

    images := []image.Image{
        imaging.New(size, size, color.RGBA{255, 0, 0, 255}),
        imaging.New(size, size, color.RGBA{0, 255, 0, 255}),
        imaging.New(size, size, color.RGBA{0, 0, 255, 255}),
    }

    spriteImg := NewSpriteImage(size, size*3)

    for _, img := range images {
        err := spriteImg.AddImage(img)
        if err != nil {
            log.Fatal(err)
        }
    }

    b, err := spriteImg.GetBytes()
    if err != nil {
        log.Fatal(err)
    }

    // Test decoding
    _, format, err := image.Decode(bytes.NewReader(b))
    if err != nil {
        log.Fatal(err)
    }
    log.Println("Format:", format)

    // Saving bytes to test.jpg
    f, err := os.Create("test.jpg")
    if err != nil {
        log.Fatal(err)
    }
    defer f.Close()
    _, err = f.Write(b)
    if err != nil {
        log.Fatal(err)
    }
}

type SpriteImage struct {
    dimentions      image.Point
    lastImgPosition image.Point
    sprite          *image.NRGBA
}

func NewSpriteImage(width, height int) SpriteImage {
    c := color.RGBA{0xff, 0xff, 0xff, 0xff}
    blankImage := imaging.New(width, height, c)

    return SpriteImage{
        dimentions:      image.Point{X: width, Y: height},
        lastImgPosition: image.Point{X: 0, Y: 0},
        sprite:          blankImage,
    }
}

func (s *SpriteImage) AddImage(img image.Image) error {
    imgWidth := img.Bounds().Dx()
    imgHeight := img.Bounds().Dy()

    // Make sure new image will fit into the sprite.
    if imgWidth != s.dimentions.X {
        return fmt.Errorf("image width %d mismatch sprite width %d", imgWidth, s.dimentions.X)
    }

    spriteHeightLeft := s.dimentions.Y - s.lastImgPosition.Y
    if imgHeight > spriteHeightLeft {
        return fmt.Errorf("image height %d won't fit into sprite, sprite free space %d ", imgHeight, s.dimentions.Y)
    }

    // add image to sprite
    s.sprite = imaging.Paste(s.sprite, img, s.lastImgPosition)

    // update next image position within sprite
    s.lastImgPosition = s.lastImgPosition.Add(image.Point{X: 0, Y: imgHeight})

    return nil
}

func (s SpriteImage) GetBytes() ([]byte, error) {
    var b bytes.Buffer
    w := bufio.NewWriter(&b)

    if s.sprite == nil {
        return nil, fmt.Errorf("sprite is nil")
    }

    if err := imaging.Encode(w, s.sprite, imaging.JPEG); err != nil {
        return nil, err
    }

    if err := w.Flush(); err != nil {
        return nil, err
    }

    return b.Bytes(), nil
}

Output:

2016/09/19 21:13:33 Format: jpeg

test.jpg:

test

from imaging.

orcaman avatar orcaman commented on July 20, 2024

Using the native jpeg encode directly seemed to have solve the issue, thanks!
I guess it may have been an issue with flushing the buffer as you suggested. Closing.

from imaging.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.