ebitenutil: Add OpenFile

This commit is contained in:
Hajime Hoshi 2016-03-07 01:29:12 +09:00
parent f59daf757e
commit 13461aa455
3 changed files with 46 additions and 19 deletions

29
ebitenutil/file.go Normal file
View File

@ -0,0 +1,29 @@
// Copyright 2016 Hajime Hoshi
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// +build !js
package ebitenutil
import (
"io"
"os"
)
// OpenFile opens a file and returns a stream for its data.
//
// This function is available both on desktops and browsers.
func OpenFile(path string) (io.ReadCloser, error) {
return os.Open(path)
}

View File

@ -20,12 +20,20 @@ import (
"bytes"
"errors"
"fmt"
"io"
"github.com/gopherjs/gopherjs/js"
"github.com/hajimehoshi/ebiten"
"image"
)
func NewImageFromFile(path string, filter ebiten.Filter) (*ebiten.Image, image.Image, error) {
type file struct {
*bytes.Reader
}
func (f *file) Close() error {
return nil
}
func OpenFile(path string) (io.ReadCloser, error) {
var err error
var content *js.Object
ch := make(chan struct{})
@ -48,18 +56,10 @@ func NewImageFromFile(path string, filter ebiten.Filter) (*ebiten.Image, image.I
req.Call("send")
<-ch
if err != nil {
return nil, nil, err
return nil, err
}
data := js.Global.Get("Uint8Array").New(content).Interface().([]uint8)
b := bytes.NewBuffer(data)
img, _, err := image.Decode(b)
if err != nil {
return nil, nil, err
}
img2, err := ebiten.NewImageFromImage(img, filter)
if err != nil {
return nil, nil, err
}
return img2, img, nil
f := &file{bytes.NewReader(data)}
return f, nil
}

View File

@ -12,14 +12,12 @@
// See the License for the specific language governing permissions and
// limitations under the License.
// +build !js
package ebitenutil
import (
"github.com/hajimehoshi/ebiten"
"image"
"os"
"github.com/hajimehoshi/ebiten"
)
// NewImageFromFile loads the file path and returns ebiten.Image and image.Image.
@ -27,7 +25,7 @@ import (
// The current directory for path depends on your environment. This will vary on your desktop or web browser.
// It'll be safer to embed your resource, e.g., with github.com/jteeuwen/go-bindata instead of using this function.
func NewImageFromFile(path string, filter ebiten.Filter) (*ebiten.Image, image.Image, error) {
file, err := os.Open(path)
file, err := OpenFile(path)
if err != nil {
return nil, nil, err
}