All Downloads are FREE. Search and download functionalities are using the official Maven repository.

se.llbit.util.ImageTools Maven / Gradle / Ivy

There is a newer version: 1.4.5
Show newest version
/* Copyright (c) 2010 Jesper Öqvist 
 *
 * This file is part of Chunky.
 *
 * Chunky is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Chunky is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License
 * along with Chunky.  If not, see .
 */
package se.llbit.util;

import javafx.scene.image.Image;
import javafx.scene.image.PixelFormat;
import javafx.scene.image.WritableImage;
import se.llbit.chunky.resources.BitmapImage;
import se.llbit.math.ColorUtil;

/**
 * Image manipulation utility methods.
 *
 * @author Jesper Öqvist 
 */
public class ImageTools {

  /**
   * Calculate the average color across an image.
   *
   * @return average color value
   */
  public static int calcAvgColor(BitmapImage image) {
    float ra = 0;
    float ga = 0;
    float ba = 0;
    float aa = 0;
    int n = 0;
    for (int x = 0; x < image.width; ++x) {
      for (int y = 0; y < image.height; ++y) {
        int cv = image.getPixel(x, y);
        float alpha = (cv >>> 24) / 255.f;
        aa += alpha;
        n++;
        ra += alpha * (0xFF & (cv >>> 16)) / 255.f;
        ga += alpha * (0xFF & (cv >>> 8)) / 255.f;
        ba += alpha * (0xFF & cv) / 255.f;
      }
    }

    if (aa == 0.f) {
      return 0;
    } else {
      return ColorUtil.getArgb(ra / aa, ga / aa, ba / aa, aa / n);
    }
  }

  /** @return a JavaFX version of a BitmapImage. */
  public static Image toFxImage(BitmapImage image) {
    WritableImage fxImage = new WritableImage(image.width, image.height);
    fxImage.getPixelWriter().setPixels(0, 0, image.width, image.height,
        PixelFormat.getIntArgbInstance(), image.data, 0, image.width);
    return fxImage;
  }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy