Loading [MathJax]/extensions/tex2jax.js

2014年7月30日水曜日

JavaFX8でPPMファイルのビューアを作る

JavaFX8でPPMファイルのビューアを作りました。 表示するだけであればこれで十分だと思います。 まじめに作るのであればPPMファイルの種類別の読み込み、ファイル形式のチェックなど色々細かいことをしないといけなさそうです。
package com.sanofc.ppm;
import java.io.IOException;
import java.io.RandomAccessFile;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.image.ImageView;
import javafx.scene.image.PixelWriter;
import javafx.scene.image.WritableImage;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class PPMViewer extends Application {
public static void main(String[] args) {
Application.launch(args);
}
public void start(Stage stage) throws IOException {
String imageUrl = this.getParameters().getRaw().get(0);
RandomAccessFile raf = new RandomAccessFile(imageUrl, "r");
String magicNumber = raf.readLine();
String[] widthAndHeight = raf.readLine().split(" ");
String maxval = raf.readLine();
int width = Integer.parseInt(widthAndHeight[0]);
int height = Integer.parseInt(widthAndHeight[1]);
WritableImage wr = new WritableImage(width, height);
PixelWriter pw = wr.getPixelWriter();
for (int y = 0; y < width; y++) {
for (int x = 0; x < height; x++) {
int r = raf.read();
int g = raf.read();
int b = raf.read();
Color color = Color.rgb(r, g, b);
pw.setColor(x, y, color);
}
}
ImageView imageView = new ImageView(wr);
Group root = new Group(imageView);
Scene scene = new Scene(root, width, height);
stage.setTitle("PPM Viewer");
stage.setScene(scene);
stage.show();
}
}
view raw PPMViewer.java hosted with ❤ by GitHub