WarpPI/desktop/src/main/java/it/cavallium/warppi/desktop/DesktopImageReader.java

75 lines
2.4 KiB
Java
Raw Normal View History

2018-09-04 12:12:41 +02:00
package it.cavallium.warppi.desktop;
2018-10-15 23:10:44 +02:00
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
2018-09-04 12:12:41 +02:00
import java.io.InputStream;
2018-10-15 23:10:44 +02:00
import javax.imageio.ImageIO;
2018-09-04 12:12:41 +02:00
import ar.com.hjg.pngj.ImageLineInt;
2019-02-27 23:29:03 +01:00
import it.cavallium.warppi.WarpPI;
2018-10-15 23:10:44 +02:00
import it.cavallium.warppi.Platform.ImageUtils.ImageReader;
2018-09-04 12:12:41 +02:00
2018-10-15 23:10:44 +02:00
public class DesktopImageReader implements ImageReader {
2018-09-04 12:12:41 +02:00
2018-10-15 23:10:44 +02:00
private ar.com.hjg.pngj.PngReader r;
2018-09-22 11:17:30 +02:00
2018-10-15 23:10:44 +02:00
public DesktopImageReader(final InputStream resourceStream) throws IOException {
2018-09-04 12:12:41 +02:00
r = new ar.com.hjg.pngj.PngReader(resourceStream);
2018-10-15 23:10:44 +02:00
// Try to read image converting it to png
if (r == null) {
final File f = File.createTempFile("picalculator-png", ".png");
f.deleteOnExit();
final BufferedImage img = ImageIO.read(resourceStream);
ImageIO.write(img, "PNG", f);
r = new ar.com.hjg.pngj.PngReader(f);
}
2018-09-04 12:12:41 +02:00
}
@Override
public int[] getImageMatrix() {
final int width = r.imgInfo.cols;
final int height = r.imgInfo.rows;
final int channels = r.imgInfo.channels;
final int[] pixels = new int[width * height];
int pi = 0;
ImageLineInt lint;
while (r.hasMoreRows()) {
lint = (ImageLineInt) r.readRow();
2018-09-22 11:17:30 +02:00
final int[] scanLine = lint.getScanline();
2018-09-04 12:12:41 +02:00
for (int i = 0; i < width; i++) {
2018-09-22 11:17:30 +02:00
final int offset = i * channels;
2018-09-04 12:12:41 +02:00
// Adjust the following code depending on your source image.
// I need the to set the alpha channel to 0xFF000000 since my destination image
// is TRANSLUCENT : BufferedImage bi = CONFIG.createCompatibleImage( width, height, Transparency.TRANSLUCENT );
// my source was 3 channels RGB without transparency
int nextPixel;
2018-09-22 11:17:30 +02:00
if (channels == 4)
nextPixel = scanLine[offset] << 16 | scanLine[offset + 1] << 8 | scanLine[offset + 2] | scanLine[offset + 3] << 24;
else if (channels == 3)
nextPixel = scanLine[offset] << 16 | scanLine[offset + 1] << 8 | scanLine[offset + 2] | 0xFF << 24;
else if (channels == 2)
nextPixel = scanLine[offset] << 16 | scanLine[offset + 1] << 8 | 0xFF | 0xFF << 24;
else
nextPixel = scanLine[offset] << 16 | scanLine[offset] << 8 | scanLine[offset] | 0xFF << 24;
2018-09-04 12:12:41 +02:00
// I'm placing the pixels on a memory mapped file
pixels[pi] = nextPixel;
pi++;
}
}
return pixels;
}
@Override
public int[] getSize() {
2018-09-22 11:17:30 +02:00
return new int[] { r.imgInfo.cols, r.imgInfo.rows };
2018-09-04 12:12:41 +02:00
}
}