LoadImage loads the image specified by the index of GLTF.Images. Image can be loaded from binary chunk file or data URI or external file..
(imgIdx int)
| 807 | // LoadImage loads the image specified by the index of GLTF.Images. |
| 808 | // Image can be loaded from binary chunk file or data URI or external file.. |
| 809 | func (g *GLTF) LoadImage(imgIdx int) (*image.RGBA, error) { |
| 810 | |
| 811 | // Check if provided image index is valid |
| 812 | if imgIdx < 0 || imgIdx >= len(g.Images) { |
| 813 | return nil, fmt.Errorf("invalid image index") |
| 814 | } |
| 815 | imgData := g.Images[imgIdx] |
| 816 | // Return cached if available |
| 817 | if imgData.cache != nil { |
| 818 | log.Debug("Fetching Image %d (cached)", imgIdx) |
| 819 | return imgData.cache, nil |
| 820 | } |
| 821 | log.Debug("Loading Image %d", imgIdx) |
| 822 | |
| 823 | var data []byte |
| 824 | var err error |
| 825 | // If Uri is empty, load image from GLB binary chunk |
| 826 | if imgData.Uri == "" { |
| 827 | if imgData.BufferView == nil { |
| 828 | return nil, fmt.Errorf("image has empty URI and no BufferView") |
| 829 | } |
| 830 | data, err = g.loadBufferView(*imgData.BufferView) |
| 831 | } else if isDataURL(imgData.Uri) { |
| 832 | // Checks if image URI is data URL |
| 833 | data, err = loadDataURL(imgData.Uri) |
| 834 | } else { |
| 835 | // Load image data from file |
| 836 | data, err = g.loadFileBytes(imgData.Uri) |
| 837 | } |
| 838 | |
| 839 | if err != nil { |
| 840 | return nil, err |
| 841 | } |
| 842 | |
| 843 | // Decodes image data |
| 844 | bb := bytes.NewBuffer(data) |
| 845 | img, _, err := image.Decode(bb) |
| 846 | if err != nil { |
| 847 | return nil, err |
| 848 | } |
| 849 | |
| 850 | // Converts image to RGBA format |
| 851 | rgba := image.NewRGBA(img.Bounds()) |
| 852 | if rgba.Stride != rgba.Rect.Size().X*4 { |
| 853 | return nil, fmt.Errorf("unsupported stride") |
| 854 | } |
| 855 | draw.Draw(rgba, rgba.Bounds(), img, image.Point{0, 0}, draw.Src) |
| 856 | |
| 857 | // Cache image |
| 858 | g.Images[imgIdx].cache = rgba |
| 859 | |
| 860 | return rgba, nil |
| 861 | } |
| 862 | |
| 863 | // bytesToArrayU32 converts a byte array to ArrayU32. |
| 864 | func (g *GLTF) bytesToArrayU32(data []byte, componentType, count int) (math32.ArrayU32, error) { |
no test coverage detected