Interpolate between pixels on an image
<p>I'm trying to implement a way to sample a texture in Java. I want this to work the same way it would by using GLSL's "texture" function. I want the neighboring pixels to be taken into account when the color is calcuated.</p>

<p>For example, say I use a float to get the image color at a certain pixel, and the number falls between two pixels. How can I calculate a mix of the neighboring pixels? Here's an image showing my goal. </p>

<p><a href="https://i.stack.imgur.com/PhuSj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PhuSj.png" alt="enter image description here"></a></p>

<p><a href="https://i.stack.imgur.com/r6vCg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/r6vCg.png" alt="enter image description here"></a></p>

<p>Is there an easy way to do this using java's BufferedImage class?</p>

<p>Here's the code I have so far, it only works for the x position at the moment.</p>

<pre><code>public static final java.awt.Color getColor(final BufferedImage image, final float x, final int y) {

    final float imageX = x * image.getWidth();

    final float decimal = imageX % 1f;

    final java.awt.Color left = new java.awt.Color(image.getRGB(Maths.clamp((int) imageX - 1, 0, image.getWidth() - 1), y));
    final java.awt.Color center = new java.awt.Color(image.getRGB(Maths.clamp((int) imageX, 0, image.getWidth() - 1), y));
    final java.awt.Color right = new java.awt.Color(image.getRGB(Maths.clamp((int) imageX + 1, 0, image.getWidth() - 1), y));

    if (decimal == 0.5f) return center;

    if (decimal &lt; 0.5f) {

        final float distanceFromCenter = 0.5f - decimal;
        final float distanceFromLeft = decimal + 0.5f;

        final Vector3f leftColor = new Vector3f(left.getRed() / 255f, left.getGreen() / 255f, left.getBlue() / 255f);
        final Vector3f centerColor = new Vector3f(center.getRed() / 255f, center.getGreen() / 255f, center.getBlue() / 255f);

        leftColor.scale(1f - distanceFromLeft);
        centerColor.scale(1f - distanceFromCenter);

        final Vector3f color = Vector3f.add(leftColor, centerColor, null);

        return new java.awt.Color(color.getX(), color.getY(), color.getZ());

    } else {

        final float distanceFromCenter = decimal - 0.5f;
        final float distanceFromRight = 1f - decimal + 0.5f;

        final Vector3f rightColor = new Vector3f(right.getRed() / 255f, right.getGreen() / 255f, right.getBlue() / 255f);
        final Vector3f centerColor = new Vector3f(center.getRed() / 255f, center.getGreen() / 255f, center.getBlue() / 255f);

        rightColor.scale(1f - distanceFromRight);
        centerColor.scale(1f - distanceFromCenter);

        final Vector3f color = Vector3f.add(rightColor, centerColor, null);

        return new java.awt.Color(color.getX(), color.getY(), color.getZ());

    }

}
</code></pre>