package org.kne.codec.kif;

import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.DataBufferInt;
import java.awt.image.DirectColorModel;
import java.awt.image.Raster;
import java.awt.image.WritableRaster;

import org.kne.membandboost.MembandBoost;

public class BufferedImageMembandBoost {
	private static final int[] MASK=new int[]{0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000};// R, G, B, A 掩码
    /**
     * 创建一个不归零的 TYPE_INT_ARGB BufferedImage
     * 使用 MembandBoost 分配未初始化的像素数组
     */
    public static BufferedImage createUninitializedBufferedImage(int width, int height) {
        int size = width * height;
        
        // 1. 创建未初始化的 DataBuffer（不归零！）
        DataBufferInt db = new DataBufferInt(
            MembandBoost.allocateUninitializedIntArray(size),
            size
        );

        // 2. 创建 ARGB Raster（4 波段，对应 TYPE_INT_ARGB）
        WritableRaster raster = Raster.createPackedRaster(
            db,
            width, height,
            width,
            MASK,  
            null
        );

        // 3. 创建匹配的 ARGB ColorModel
        ColorModel colorModel = ColorModel.getRGBdefault();

        // 4. 创建 BufferedImage
        return new BufferedImage(
            colorModel,
            raster,
            false,   // isRasterPremultiplied
            null
        );
    }

    /**
     * 从已有的 int[] 像素数据创建 BufferedImage（不拷贝）
     */
    public static BufferedImage createFromPixels(int[] pixels, int width, int height) {
        int size = width * height;
        if (pixels.length < size) {
            throw new IllegalArgumentException("pixels 数组长度不足");
        }

        DataBufferInt db = new DataBufferInt(pixels, size);
        WritableRaster raster = Raster.createPackedRaster(
            db,
            width, height,
            width,
            MASK,
            null
        );

        ColorModel colorModel = ColorModel.getRGBdefault();

        return new BufferedImage(colorModel, raster, false, null);
    }
}