Permalink
Browse files

Implemented saving for jpgs

  • Loading branch information...
tobi committed May 14, 2012
1 parent 55b95af commit 15960097c071892c75a8fc8c02890a8d629b047b
Showing with 50 additions and 2 deletions.
  1. +29 −1 gd.go
  2. +12 −0 image_test.go
  3. +9 −1 jpg.go
View
30 gd.go
@@ -13,6 +13,7 @@ import (
var (
imageError = errors.New("image is nil")
+ writeError = errors.New("image cannot be accessed")
)
type gdImage struct {
@@ -32,7 +33,7 @@ func img(img *C.gdImage) *gdImage {
}
func gdCreate(sx, sy int) *gdImage {
- return img(C.gdImageCreate(C.int(sx), C.int(sy)))
+ return img(C.gdImageCreateTrueColor(C.int(sx), C.int(sy)))
}
func gdCreateFromJpeg(buffer []byte) *gdImage {
@@ -87,3 +88,30 @@ func (p *gdImage) gdCopyResized(dst *gdImage, dstX, dstY, srcX, srcY, dstW, dstH
C.gdImageCopyResized(dst.img, p.img, C.int(dstX), C.int(dstY), C.int(srcX), C.int(srcY),
C.int(dstW), C.int(dstH), C.int(srcW), C.int(srcH))
}
+
+// func (p *gdImage) gdImagePng() ([]byte, error) {
+// var size int
+
+// data := C.gdImagePngPtr(p.img, &size)
+// if data == nil {
+// return []byte{}, writeError
+// }
+
+// defer C.gdFree(unsafe.Pointer(data))
+
+// return C.GoBytes(data)
+// }
+
+func (p *gdImage) gdImageJpeg() ([]byte, error) {
+ var size C.int
+
+ // use -1 as quality, this will mean to use standard Jpeg quality
+ data := C.gdImageJpegPtr(p.img, &size, -1)
+ if data == nil || int(size) == 0 {
+ return []byte{}, writeError
+ }
+
+ defer C.gdFree(unsafe.Pointer(data))
+
+ return C.GoBytes(data, size), nil
+}
View
@@ -87,6 +87,18 @@ func TestResampleFailure(t *testing.T) {
}
}
+func TestSave(t *testing.T) {
+ img := asset("./assets/image.jpg")
+ defer img.Destroy()
+
+ resized, _ := img.NewResampled(100, 100)
+
+ dest, _ := os.Create("/tmp/dest.jpg")
+ defer dest.Close()
+ resized.WriteTo(dest)
+
+}
+
// func TestSaveToSuccess(t *testing.T) {
// img := Open("./assets/image.jpg")
View
10 jpg.go
@@ -61,7 +61,15 @@ func (img *Jpg) ReadFrom(reader io.Reader) (n int64, err error) {
}
func (img *Jpg) WriteTo(writer io.Writer) (n int64, err error) {
- return 0, nil
+
+ slice, err := img.gd.gdImageJpeg()
+ if err != nil {
+ return 0, err
+ }
+
+ _, err = writer.Write(slice)
+
+ return 0, err
}
func (img *Jpg) Width() int {

0 comments on commit 1596009

Please sign in to comment.