Created
December 21, 2015 15:28
-
-
Save james-d/4376831966915e7af883 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.nio.ByteBuffer; | |
import javafx.application.Application; | |
import javafx.scene.Scene; | |
import javafx.scene.image.Image; | |
import javafx.scene.image.PixelReader; | |
import javafx.scene.image.WritablePixelFormat; | |
import javafx.scene.layout.Pane; | |
import javafx.scene.paint.Color; | |
import javafx.scene.shape.Line; | |
import javafx.scene.shape.Rectangle; | |
import javafx.stage.Stage; | |
public class ImageToByteArray extends Application { | |
@Override | |
public void start(Stage primaryStage) { | |
Rectangle rect = new Rectangle(200, 80, Color.NAVY); | |
Line upDiag = new Line(0, 80, 200, 0); | |
upDiag.setStroke(Color.WHITE); | |
upDiag.setStrokeWidth(10); | |
Line downDiag = new Line(0, 0, 200, 80); | |
downDiag.setStroke(Color.WHITE); | |
downDiag.setStrokeWidth(10); | |
Pane flag = new Pane(rect, upDiag, downDiag); | |
Scene scene = new Scene(flag, 200, 80); | |
primaryStage.setScene(scene); | |
primaryStage.show(); | |
Image img = flag.snapshot(null, null); | |
PixelReader pr = img.getPixelReader(); | |
WritablePixelFormat<ByteBuffer> pixelformat = WritablePixelFormat.getByteBgraInstance(); | |
int w = (int) img.getWidth(); | |
int h = (int) img.getHeight(); | |
int offset = 0; | |
int scanlineStride = w * 4; | |
byte[] buffer = new byte[w * h * 4]; | |
pr.getPixels(0, 0, w, h, pixelformat, buffer, offset, scanlineStride); | |
// portion near the center: | |
for (int i = 30780; i < 30880; i++) System.out.println(Byte.toUnsignedInt(buffer[i])); | |
} | |
public static void main(String[] args) { | |
launch(args); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment