Skip to content

Instantly share code, notes, and snippets.

@justinfx
Created August 23, 2016 10:53
Show Gist options
  • Save justinfx/4ae8884131c4fbbef373cfd7f7ef259c to your computer and use it in GitHub Desktop.
Save justinfx/4ae8884131c4fbbef373cfd7f7ef259c to your computer and use it in GitHub Desktop.
Example of converting OpenImageIO ColorData float32 rgb pixel values into stdlib image; Encode to JPEG
/*
Example of taking an OpenColorIO ColorData and converting
it into a stdlib Image. Then encoding to jpeg format.
Ref: https://github.com/justinfx/opencolorigo/issues/1
Author: Justin Israel ([email protected])
*/
package main
import (
"bufio"
"image"
"image/jpeg"
"os"
)
const maxRgb = 255.999
// ColorData is a slice of float32 color values
// representing rgbrgbrgb...
type ColorData []float32
// FloatToInt converts a float color component value
// into an 8bit value (0-255)
func FloatToInt(f float32) uint8 {
return uint8(f * maxRgb)
}
// ColorDataToImage converts ColorData float pixels
// into an *image.RGBA
func ColorDataToImage(pixels ColorData, w, h int) *image.RGBA {
// Properly sized blank image
img := image.NewRGBA(image.Rect(0, 0, w, h))
j := 0
comp := 1 // which color component we are on
// Set each R,G,B,A component of the image
for i := range img.Pix {
// Handle Alpha
if comp == 4 {
img.Pix[i] = 255
comp = 1
continue
}
// Handle color convert
img.Pix[i] = FloatToInt(pixels[j])
j += 1
comp += 1
}
return img
}
// Make some random ColorData pixel data in format of:
// rgbrgbrgb...
func createImageData(w, h int) ColorData {
imageData := make(ColorData, w*h*3)
for i := range imageData {
imageData[i] = 0.5
}
return imageData
}
func main() {
w := 512
h := 512
// Some random ColorData for a given image size
imageData := createImageData(w, h)
// Convert ColorData to *image.RGBA
img := ColorDataToImage(imageData, w, h)
// Encode to jpeg
out, _ := os.Create("out.jpg")
err := jpeg.Encode(bufio.NewWriter(out), img, nil)
if err != nil {
panic(err.Error())
}
}
@cnjack
Copy link

cnjack commented Aug 23, 2016

haha, My code just add thego func to this, mayBe it is faster,I will tip my code if it works

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment