Java - drawing many images with Graphics.drawImage() and 2-screen buffer strategy distorts and cuts images - image

I am using a loop to invoke double buffering painting. This, together with overriding my only Panel's repaint method, is designed to pass complete control of repaint to my loop and only render when it necessary (i.e. some change was made in the GUI).
This is my rendering routine:
Log.write("renderer painting");
setNeedsRendering(false);
Graphics g = frame.getBufferStrategy().getDrawGraphics();
g.setFont(font);
g.setColor(Color.BLACK);
g.fillRect(0, 0, window.getWidth(),window.getHeight());
if(frame != null)
window.paint(g);
g.dispose();
frame.getBufferStrategy().show();
As you can see, it is pretty standard. I get the grpahics object from the buffer strategy (initialized to 2), make it all black and pass it to the paint method of my "window" object.
After window is done using the graphics object, I dispose of it and invoke show on the buffer strategy to display the contents of the virtual buffer.
It is important to note that window passes the graphics object to many other children components the populate the window and each one, in turn, uses the same instance of the graphics object to draw something onto the screen: text, shapes, or images.
My problem begins to show when the system is running and a large image is rendered. The image appears to be cut into seveeal pieces and drawn again and again (3-4 times) with different offsets inside of where the image is supposed to be rendered. See my attached images:
This is the original image:
alt text http://img109.imageshack.us/img109/8308/controller.png
This is what I get:
alt text http://img258.imageshack.us/img258/3248/probv.png
Note that in the second picture, I am rendering shapes over the picture - these are always at the correct position.
Any idea why this is happening?
If I save the image to file, as it is in memory, right before the call to g.drawImage(...) it is identical to the original.

Uh, you are using Swing ?
Normally Swing automatically renders the image, you can't switch it off. The repaint()
method is out of bounds because Swing has a very complicated rendering routine due to
method compatibility for AWT widgets and several optimizations, inclusive drawing only
when necessary !
If you want to use the High-Speed Drawing API, you use a component with a BufferStrategy
like JFrame and Window, use
setIgnoreRepaint(false);
to switch off Swing rendering, set up a drawing loop and paint the content itself.
Or you can use JOGL for OpenGL rendering. The method you are using seems completely
at odds with correct Java2D usage.
Here the correct use:
public final class FastDraw extends JFrame {
private static final transient double NANO = 1.0e-9;
private BufferStrategy bs;
private BufferedImage frontImg;
private BufferedImage backImg;
private int PIC_WIDTH,
PIC_HEIGHT;
private Timer timer;
public FastDraw() {
timer = new Timer(true);
JMenu menu = new JMenu("Dummy");
menu.add(new JMenuItem("Display me !"));
menu.add(new JMenuItem("Display me, too !"));
JMenuBar menuBar = new JMenuBar();
menuBar.add(menu);
setJMenuBar(menuBar);
setIgnoreRepaint(true);
setVisible(true);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent evt) {
super.windowClosing(evt);
timer.cancel();
dispose();
System.exit(0);
}
});
try {
backImg = javax.imageio.ImageIO.read(new File("MyView"));
frontImg = javax.imageio.ImageIO.read(new File("MyView"));
}
catch (IOException e) {
System.out.println(e.getMessage());
}
PIC_WIDTH = backImg.getWidth();
PIC_HEIGHT = backImg.getHeight();
setSize(PIC_WIDTH, PIC_HEIGHT);
createBufferStrategy(1); // Double buffering
bs = getBufferStrategy();
timer.schedule(new Drawer(),0,20);
}
public static void main(String[] args) {
new FastDraw();
}
private class Drawer extends TimerTask {
private VolatileImage img;
private int count = 0;
private double time = 0;
public void run() {
long begin = System.nanoTime();
Graphics2D g = (Graphics2D) bs.getDrawGraphics();
GraphicsConfiguration gc = g.getDeviceConfiguration();
if (img == null)
img = gc.createCompatibleVolatileImage(PIC_WIDTH, PIC_HEIGHT);
Graphics2D g2 = img.createGraphics();
// Zeichenschleife
do {
int valStatus = img.validate(gc);
if (valStatus == VolatileImage.IMAGE_OK)
g2.drawImage(backImg,0,0,null);
else {
g.drawImage(frontImg, 0, 0, null);
}
// volatile image is ready
g.drawImage(img,0,50,null);
bs.show();
} while (img.contentsLost());
time = NANO*(System.nanoTime()-begin);
count++;
if (count % 100 == 0)
System.out.println(1.0/time);
}
}

Related

libgdx fails to load textures after some time

So I'm making a zombie shooter game that works well, but after running for a while I get hit with this exception:
Exception in thread "LWJGL Application" com.badlogic.gdx.utils.GdxRuntimeException:
Couldn't load file: 1zom3.png
at com.badlogic.gdx.graphics.Pixmap.<init>(Pixmap.java:140)
at com.badlogic.gdx.graphics.TextureData$Factory.loadFromFile(TextureData.java:98)
at com.badlogic.gdx.graphics.Texture.<init>(Texture.java:100)
at com.badlogic.gdx.graphics.Texture.<init>(Texture.java:92)
at com.lastride.game.Entity.changeState(Entity.java:51)
at com.lastride.game.Enemy.seek(Enemy.java:39)
at com.lastride.game.LastRideGame.update(LastRideGame.java:149)
at com.lastride.game.LastRideGame.render(LastRideGame.java:229)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:215)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:120)
Caused by: java.io.IOException: Error loading pixmap:
at com.badlogic.gdx.graphics.g2d.Gdx2DPixmap.<init>(Gdx2DPixmap.java:57)
at com.badlogic.gdx.graphics.Pixmap.<init>(Pixmap.java:138)
... 9 more
I know for a fact that the image is there as it works, but it seems that after running for a bit it crashes.
This is the method where it crashes on:
public void changeState(int i)
{
//changes the state and concurrently the image associated with the given state
state = i;
sprite = new Sprite(new Texture(Gdx.files.internal(name+i+suff)));//crashes here
bounding = (sprite.getBoundingRectangle());
if (sprite.getTexture().getTextureData().isPrepared()==false)
{
sprite.getTexture().getTextureData().prepare();
}
playerMap = sprite.getTexture().getTextureData().consumePixmap();
}
As #Tenfour04 points out, it could be an out-of-memory problem.
Instead of doing this:
sprite = new Sprite(new Texture(Gdx.files.internal(name+i+suff)));
Create an global (and/or possible static and/or possible final) Texture object, and load it just once at the beginning of your game and use it repeatably.
Something like this:
public static Texture myTexture_1; //<< your texture
public static final int ID_MY_TEXTURE_1 = 1; //<< this will work as an ID
// This method is called once in your game (like in the create() method)...
public static void load() {
myTexture_1 = new Texture(Gdx.files.internal(name + ID_MY_TEXTURE_1 + suff));
}
// when no longer necessary, remove it...
public static void dispose() {
myTexture_1.dispose();
// and so on...
}
then, in your changeState() method, do a switch to retrieve the correct texture:
public void changeState(int i) {
state = i;
switch(i){
case ID_MY_TEXTURE_1 :
sprite = new Sprite(myTexture_1);
break;
// rest of cases...
}
// rest of your code...
}

Custom Node painting in JavaFX

In PySide you can override the paintEvent() method of a QWidget to control how the widget is painted on the screen. Is there an equivalent for Node in JavaFX?
In context: I'm in need of a way to display a custom image format on the screen. Constantly converting my format and JavaFX's Image so I can display it in an ImageView is too slow for me, in addition to being messier.
I've taken a look at ImageView.java and Canvas.java, but no luck. ImageView is using css, and Canvas appears to be doing something with the deprecated impl_ methods, for which I've found no documentation on.
Thanks!
Generally, the paint mechanisms in JavaFX changed towards a more event-based approach. To follow the JavaFX way, you should probably look at Timeline or AnimationTimer and only update the display when the actual image data changes.
However, you could use the old Swing way in JavaFX, if you like:
public class MyPane extends Pane {
private final Canvas canvas;
public MyPane() {
canvas = new Canvas(getWidth(), getHeight());
getChildren().add(canvas);
widthProperty().addListener(e -> canvas.setWidth(getWidth()));
heightProperty().addListener(e -> canvas.setHeight(getHeight()));
}
#Override
protected void layoutChildren() {
super.layoutChildren();
GraphicsContext gc = canvas.getGraphicsContext2D();
gc.clearRect(0, 0, getWidth(), getHeight());
gc.setFill(Color.RED);
gc.fillRect(10, 10, getWidth() - 20, getHeight() - 20);
// Paint your custom image here:
gc.drawImage(someImage, 0, 0);
}
}
The above code would be the equivalence of this Swing code:
public class MyPanel extends JPanel {
private static final long serialVersionUID = -969772195113348076L;
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.clearRect(0, 0, getWidth(), getHeight());
g.setColor(java.awt.Color.RED);
g.fillRect(10, 10, getWidth() - 20, getHeight() - 20);
// Paint your custom image here:
g.drawImage(someImage, 0, 0, null);
}
}

Create more than one window of a single sketch in Processing

How to create more than one window of a single sketch in Processing?
Actually I want to detect and track a particular color (through webcam) in one window and display the detected co-ordinates as a point in another window.Till now I'm able to display the points in the same window where detecting it.But I want to split it into two different windows.
You need to create a new frame and a new PApplet... here's a sample sketch:
import javax.swing.*;
SecondApplet s;
void setup() {
size(640, 480);
PFrame f = new PFrame(width, height);
frame.setTitle("first window");
f.setTitle("second window");
fill(0);
}
void draw() {
background(255);
ellipse(mouseX, mouseY, 10, 10);
s.setGhostCursor(mouseX, mouseY);
}
public class PFrame extends JFrame {
public PFrame(int width, int height) {
setBounds(100, 100, width, height);
s = new SecondApplet();
add(s);
s.init();
show();
}
}
public class SecondApplet extends PApplet {
int ghostX, ghostY;
public void setup() {
background(0);
noStroke();
}
public void draw() {
background(50);
fill(255);
ellipse(mouseX, mouseY, 10, 10);
fill(0);
ellipse(ghostX, ghostY, 10, 10);
}
public void setGhostCursor(int ghostX, int ghostY) {
this.ghostX = ghostX;
this.ghostY = ghostY;
}
}
One option might be to create a sketch twice the size of your original window and just offset the detected coordinates by half the sketch's size.
Here's a very rough code snippet (assumming blob will be a detected color blob):
int camWidth = 320;
int camHeight = 240;
Capture cam;
void setup(){
size(camWidth * 2,camHeight);
//init cam/opencv/etc.
}
void draw(){
//update cam and get data
image(cam,0,0);
//draw
rect(camWidth+blob.x,blob.y,blob.width,blob.height);
}
To be honest, it might be easier to overlay the tracked information. For example, if you're doing color tracking, just display the outlines of the bounding box of the tracked area.
If you really really want to display another window, you can use a JPanel.
Have a look at this answer for a running code example.
I would recommend using G4P, a GUI library for Processing that has some functionality built in for handling multiple windows. I have used this before with a webcam and it worked well. It comes with a GWindow object that will spawn a window easily. There is a short tutorial on the website that explains the basics.
I've included some old code that I have that will show you the basic idea. What is happening in the code is that I make two GWindows and send them each a PImage to display: one gets a webcam image and the other an effected image. The way you do this is to augment the GWinData object to also include the data you would like to pass to the windows. Instead of making one specific object for each window I just made one object with the two PImages in it. Each GWindow gets its own draw loop (at the bottom of the example) where it loads the PImage from the overridden GWinData object and displays it. In the main draw loop I read the webcam and then process it to create the two images and then store them into the GWinData object.
Hopefully that gives you enough to get started.
import guicomponents.*;
import processing.video.*;
private GWindow window;
private GWindow window2;
Capture video;
PImage sorted;
PImage imgdif; // image with pixel thresholding
MyWinData data;
void setup(){
size(640, 480,P2D); // Change size to 320 x 240 if too slow at 640 x 480
// Uses the default video input, see the reference if this causes an error
video = new Capture(this, 640, 480, 24);
numPixels = video.width * video.height;
data = new MyWinData();
window = new GWindow(this, "TEST", 0,0, 640,480, true, P2D);
window.isAlwaysOnTop();
window.addData(data);
window.addDrawHandler(this, "Window1draw");
window2 = new GWindow(this, "TEST", 640,0 , 640,480, true, P2D);
window2.isAlwaysOnTop();
window2.addData(data);
window2.addDrawHandler(this, "Window2draw");
loadColors("64rev.csv");
colorlength = mycolors.length;
distances = new float[colorlength];
noCursor();
}
void draw()
{
if (video.available())
{
background(0);
video.read();
image(video,0,0);
loadPixels();
imgdif = get(); // clones the last image drawn to the screen v1.1
sorted = get();
/// Removed a lot of code here that did the processing
// hand data to our data class to pass to other windows
data.sortedimage = sorted;
data.difimage = imgdif;
}
}
class MyWinData extends GWinData {
public PImage sortedimage;
public PImage difimage;
MyWinData(){
sortedimage = createImage(640,480,RGB);
difimage = createImage(640,480,RGB);
}
}
public void Window1draw(GWinApplet a, GWinData d){
MyWinData data = (MyWinData) d;
a.image(data.sortedimage, 0,0);
}
public void Window2draw(GWinApplet a, GWinData d){
MyWinData data = (MyWinData) d;
a.image(data.difimage,0,0);
}

Transition of images in Windows Forms Picture box

I'm new to Windows Forms, in my project, i need to change the image in the picture box at runtime. I'm able to do that with the help of a timer. The picture just gets changed. Is it possible to do some transitions when image changes, for example fade in, fade out, blur etc.. If possible could some one please let me know how to do it. I searched in net but in vain.Thanks in advance.
Varun
Simply take new code file and paste below code in it
an original answer for the similar question, answer taken from another question
Answer
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Windows.Forms;
public class BlendPanel : Panel
{
private Image mImg1;
private Image mImg2;
private float mBlend;
public BlendPanel()
{
SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.OptimizedDoubleBuffer, true);
}
public Image Image1
{
get { return mImg1; }
set { mImg1 = value; Invalidate(); }
}
public Image Image2
{
get { return mImg2; }
set { mImg2 = value; Invalidate(); }
}
public float Blend
{
get { return mBlend; }
set { mBlend = value; Invalidate(); }
}
protected override void OnPaint(PaintEventArgs e)
{
if (mImg1 == null || mImg2 == null)
e.Graphics.FillRectangle(new SolidBrush(this.BackColor), new Rectangle(0, 0, this.Width, this.Height));
else
{
Rectangle rc = new Rectangle(0, 0, this.Width, this.Height);
ColorMatrix cm = new ColorMatrix();
ImageAttributes ia = new ImageAttributes();
cm.Matrix33 = mBlend;
ia.SetColorMatrix(cm);
e.Graphics.DrawImage(mImg2, rc, 0, 0, mImg2.Width, mImg2.Height, GraphicsUnit.Pixel, ia);
cm.Matrix33 = 1F - mBlend;
ia.SetColorMatrix(cm);
e.Graphics.DrawImage(mImg1, rc, 0, 0, mImg1.Width, mImg1.Height, GraphicsUnit.Pixel, ia);
}
base.OnPaint(e);
}
}
Build your project. You can now drop a BlendPanel from the top of the toolbox onto your form. Here's a sample program that uses it:
private float mBlend;
private int mDir = 1;
public int count = 0;
public Bitmap[] pictures;
public void myPhoto()
{
pictures = new Bitmap[9];
pictures[0] = new Bitmap(#"Library Images\cf3.jpg");
pictures[1] = new Bitmap(#"Library Images\cf4.jpg");
pictures[2] = new Bitmap(#"Library Images\l1.JPG");
pictures[3] = new Bitmap(#"Library Images\l2.JPG");
pictures[4] = new Bitmap(#"Library Images\l3.JPG");
pictures[5] = new Bitmap(#"Library Images\l4.JPG");
pictures[6] = new Bitmap(#"Library Images\l5.JPG");
pictures[7] = new Bitmap(#"Library Images\l6.JPG");
pictures[8] = new Bitmap(#"Library Images\l7.JPG");
timer1.Interval = 50; //time of transition
timer1.Tick += BlendTick;
try
{
blendPanel1.Image1 = pictures[count];
blendPanel1.Image2 = pictures[++count];
}
catch
{
}
timer1.Enabled = true;
}
private void BlendTick(object sender, EventArgs e)
{
mBlend += mDir * 0.02F;
if (mBlend > 1)
{
mBlend = 0.0F;
if ((count + 1) < pictures.Length)
{
blendPanel1.Image1 = pictures[count];
blendPanel1.Image2 = pictures[++count];
}
else
{
blendPanel1.Image1 = pictures[count];
blendPanel1.Image2 = pictures[0];
count = 0;
}
}
blendPanel1.Blend = mBlend;
}
You'll need to modify the new Bitmap(#"yourimagePath"); calls. Build and run. You should see the displayed image smoothly morph from your first image to your second image without any flickering.
I hope it helps for other...
There is no built-in support for such effects, but you can implement them. I'd suggest to write a custom control that renders the image and have a method for fade-swap, fade itself can be reached with alpha-blending drawing with .NET Graphics class.
However, Graphics class isn't very fast, I don't recommend to use this technique for big images. If you need some fancy UI with hw-accelerated effects, take a look at WPF.
Blend effects are easy to get going by using the ColorMatrix class. There's a good example available in my answer in this thread.
A simple way to get a blur is to resize the image, making it smaller, then redraw it back, making it larger. The Graphics.InterpolationMode property affects the type of blur you'll get.
Those are quicky do-it-yourself solutions. Any decent graphics library has these kind of operations built-in. You probably want something free, check out ImageMagick.NET
To put it simply, not without external (3rd-party) libraries.

load images dynamically on scroll in blackberry

How to display images in the form of pages where only one page is displayed at a time on blackberry screen. On scrolling down subsequent images will load at run time. So that loading of images do not consume time at startup.
Edit: I am using loadimage function which loads images from blackberry device memory which loads images from specified path and resizing them.As number of images increases, it increases the startup time during opening of window.There is an in-built application(Media) in blackberry phone, where images load without taking any extra time. My idea is to display particular number of images which fit to the blackberry screen. As user scroll down to bottom of screen, application will then load and display more images. So my question is how to detect when user reached to bottom of blackberry screen and display one more row images.
Keep array of images url and current image index. Put a BitmapField on screen. Add menu items for Next/Prev. On Next load Bitmap from incremented index url, set it to BitmapField and invalidate screen. On Prev do the same with decremented index.
you can use button as well (maybe in storm) but menu is obligatory
load images in separate threads (especially if they are stored in web)
you can implement caching (in app memory or by saving images on device storage)
some text field may be helpful (file name, type, size, dimentions etc)
UPDATE
For this purpose you can use ScrollChangeListener
try this code:
class Scr extends MainScreen implements ScrollChangeListener {
static int mRowNumber = 0;
public Scr() {
getMainManager().setScrollListener(this);
//preload some images on the start
for (int i = 0; i < 20; i++) {
mRowNumber = i;
add(new BitmapField(downloadBitmap(), FOCUSABLE));
}
}
public static Bitmap downloadBitmap() {
Bitmap result = new Bitmap(200, 80);
Graphics g = new Graphics(result);
g.drawRect(0, 0, 200, 80);
g.drawText("row #" + String.valueOf(mRowNumber), 30, 30);
return result;
}
public void scrollChanged(final Manager manager, int newHorizontalScroll,
int newVerticalScroll) {
int testBottomScroll = manager.getVirtualHeight()
- manager.getVisibleHeight();
if (testBottomScroll == newVerticalScroll) {
mRowNumber++;
(new Thread(new Runnable() {
public void run() {
// simulating download
Bitmap bitmap = downloadBitmap();
// update ui in thread safe way
addBitmap(bitmap);
}
})).start();
}
}
public void addBitmap(final Bitmap bitmap) {
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
getMainManager().add(new BitmapField(bitmap, FOCUSABLE));
}
});
}
}
PS the problem with this approach is you will be able to catch scroll event only if there are enough images on screen. Consider using Screen.navigationMovement(int, int, int, int) then. And don't forget to test it with trackwheel and touchscreen.
Btw my opinion is that it would be better to load all images at once using some thread queue (so images will be loaded asynchronously without locking ui)

Resources