How to replace default image when user selected image? - java

I have one default image and I want to replace the image when the user or the program already selected an image. I have only the basic image reader for displaying the default image.
private static void loadImage()throws Exception{
File image2 = new File("...Example\\blackimage.jpg");
bi = ImageIO.read(image2);
}

You could override methods so
private static void loadImage(String imagePath) throws Exception {
File image2 = new File(imagePath);
bi = ImageIO.read(image2);
}
private static void loadImage() throws Exception {
loadImage("...Example\\blackimage.jpg");
}
This would give you two methods, one to call if you have a image in mind and one for the default image.
If your program already has one selected for a particular user, for example stored in some sort of local storage / database, it can call the first method, however if an image is not found it can call the default no parameter method.

Related

How to fix java heap space out of memory when using many successive images

Trying to perform some printings using JasperReport.
JasperReport provides a function to print a document to a BufferedImage, which i convert to a WritableImage to display it on an ImageView object (as shown in the code below).
By time i get a Java Heap space out of memory exception in the getImage(int pageNumber) function. My guess is that the old references to the images are not freed.
Is it possible to fix that ?
private void viewPage(int pageNumber) throws JRException {
this.resultViewer.setFitHeight(this.imageHeight * this.zoomFactor);
this.resultViewer.setFitWidth(this.imageWidth * this.zoomFactor);
this.resultViewer.setImage(this.getImage(pageNumber));
}
#FXML
private ImageView resultViewer;
private WritableImage getImage(int pageNumber) throws JRException {
return SwingFXUtils
.toFXImage((BufferedImage) JasperPrintManager.printPageToImage(this.jasperPrint, pageNumber, 2), null);
}
I fixed the problem by caling flush() function on the last displayed BufferedImage before displaying a next one

Accessing Images from image folder in JAVA

I'm beginner to java GUI. And want to access images from the folder but i'm getting the following error.
My Code
import java.awt.Image;
import javax.swing.ImageIcon;
public class Images {
private static String IMG_FOLDER = "C:/Users/RASHID/workspace/images/";
public static Image ICON = getImage(IMG_FOLDER + "icon.png");
private static Images instance;
private Images() {}
public static Images getInstance() {
if(instance==null)
instance = new Images();
return instance;
}
public static Image getImage(String image){
return getImageIcon(image).getImage();
}
public static ImageIcon getImageIcon(String image){
return new ImageIcon(getInstance().getClass().getClassLoader().getResource(image));
}
}
When i try to run this one in main i get the following Errors. I don't know whats happening here.
Exception in thread "main" java.lang.ExceptionInInitializerError
Caused by: java.lang.NullPointerException
at javax.swing.ImageIcon.<init>(Unknown Source)
at Images.getImageIcon(Images.java:38)
at Images.getImage(Images.java:34)
at Images.<clinit>(Images.java:9)
You don't use classloaders to fetch files from hard drive. Instead, you need to fetch them as Files and transform to Images first:
File sourceimage = new File("c:\\mypic.jpg");
Image image = ImageIO.read(sourceimage);
return new ImageIcon(image);
(taken directly from this site - take a look)
You are trying to construct ImageIcon object using a constroctur that takes URL paramter (because getResource() method returns URL object, and by the way in this case it returns null, hence NullPointerException)
You should use ImageIcon(String filename) constructor instead, which will create ImageIcon from the file specified.
Read from Local Folder
File sourceimage = new File("c:\\picture_name.jpeg");
Image image = ImageIO.read(sourceimage);

Usage of Proxy design pattern

I tried to understand proxy design pattern. But i could not understand the usage of the proxy design pattern. i got this code example from wikipedia
interface Image {
public void displayImage();
}
//on System A
class RealImage implements Image {
private String filename = null;
/**
* Constructor
* #param filename
*/
public RealImage(final String filename) {
this.filename = filename;
loadImageFromDisk();
}
/**
* Loads the image from the disk
*/
private void loadImageFromDisk() {
System.out.println("Loading " + filename);
}
/**
* Displays the image
*/
public void displayImage() {
System.out.println("Displaying " + filename);
}
}
//on System B
class ProxyImage implements Image {
private RealImage image = null;
private String filename = null;
/**
* Constructor
* #param filename
*/
public ProxyImage(final String filename) {
this.filename = filename;
}
/**
* Displays the image
*/
public void displayImage() {
if (image == null) {
image = new RealImage(filename);
}
image.displayImage();
}
}
class ProxyExample {
/**
* Test method
*/
public static void main(String[] args) {
final Image IMAGE1 = new ProxyImage("HiRes_10MB_Photo1");
final Image IMAGE2 = new ProxyImage("HiRes_10MB_Photo2");
IMAGE1.displayImage(); // loading necessary
IMAGE1.displayImage(); // loading unnecessary
IMAGE2.displayImage(); // loading necessary
IMAGE2.displayImage(); // loading unnecessary
IMAGE1.displayImage(); // loading unnecessary
}
}
In this example they said loading is unnecessary for second time of dispalyImage. Even it is possible in directly accessing the RealImage object too.
final Image IMAGE1 = new RealImage("HiRes_10MB_Photo1");
final Image IMAGE2 = new RealImage("HiRes_10MB_Photo2");
IMAGE1.displayImage(); // loading necessary
IMAGE1.displayImage(); // loading unnecessary
IMAGE2.displayImage(); // loading necessary
IMAGE2.displayImage(); // loading unnecessary
IMAGE1.displayImage(); // loading unnecessary
I need to understand the usage of the ProxyImage class in this pattern.
You know, I agree with you. I feel like there's a much better example they could have used for the proxy pattern. This seems to use the same example but it's explained much better. You should look at that instead.
Basically, it all comes down to this comment:
// create the Image Object only when the image is required to be shown
That is the benefit the proxy gives you in this example. If you don't display the image, you don't pay the penalty of loading it:
package proxy;
/**
* Image Viewer program
*/
public class ImageViewer {
public static void main(String[] args) {
// assuming that the user selects a folder that has 3 images
//create the 3 images
Image highResolutionImage1 = new ImageProxy("sample/veryHighResPhoto1.jpeg");
Image highResolutionImage2 = new ImageProxy("sample/veryHighResPhoto2.jpeg");
Image highResolutionImage3 = new ImageProxy("sample/veryHighResPhoto3.jpeg");
// assume that the user clicks on Image one item in a list
// this would cause the program to call showImage() for that image only
// note that in this case only image one was loaded into memory
highResolutionImage1.showImage();
// consider using the high resolution image object directly
Image highResolutionImageNoProxy1 = new HighResolutionImage("sample/veryHighResPhoto1.jpeg");
Image highResolutionImageNoProxy2 = new HighResolutionImage("sample/veryHighResPhoto2.jpeg");
Image highResolutionImageBoProxy3 = new HighResolutionImage("sample/veryHighResPhoto3.jpeg");
// assume that the user selects image two item from images list
highResolutionImageNoProxy2.showImage();
// note that in this case all images have been loaded into memory
// and not all have been actually displayed
// this is a waste of memory resources
}
}
Proxy means ‘in place of’, representing’ or the authority to represent someone else, or a figure that can be used to represent the value of something.
Proxy design pattern is also called surrogate, handle, and wrapper.
It is used when we want to create a wrapper to cover the main object's complexity from the client.
Some real world examples of Proxy Design Pattern:
A bank's cheque or credit card is a proxy for what is in our bank account. It can be used in place of cash, and provides a means of accessing that cash when required. And that’s exactly what the Proxy pattern does – “Controls and manage access to the object they are protecting“.
A company or corporate used to have a proxy which restricts few site access. The proxy first checks the host you are connecting to, if it is not a part of restricted site list, then it connects to the real internet.

Proxy pattern - Loading into memory

I am looking at a code sample that explains the proxy pattern. Here is the code:
/**
* Proxy
*/
public class ImageProxy implements Image {
/**
* Private Proxy data
*/
private String imageFilePath;
/**
* Reference to RealSubject
*/
private Image proxifiedImage;
public ImageProxy(String imageFilePath) {
this.imageFilePath= imageFilePath;
}
#Override
public void showImage() {
// create the Image Object only when the image is required to be shown
proxifiedImage = new HighResolutionImage(imageFilePath);
// now call showImage on realSubject
proxifiedImage.showImage();
}
}
/**
* RealSubject
*/
public class HighResolutionImage implements Image {
public HighResolutionImage(String imageFilePath) {
loadImage(imageFilePath);
}
private void loadImage(String imageFilePath) {
// load Image from disk into memory
// this is heavy and costly operation
}
#Override
public void showImage() {
// Actual Image rendering logic
}
}
/**
* Image Viewer program
*/
public class ImageViewer {
public static void main(String[] args) {
// assuming that the user selects a folder that has 3 images
//create the 3 images
Image highResolutionImage1 = new ImageProxy("sample/veryHighResPhoto1.jpeg");
Image highResolutionImage2 = new ImageProxy("sample/veryHighResPhoto2.jpeg");
Image highResolutionImage3 = new ImageProxy("sample/veryHighResPhoto3.jpeg");
// assume that the user clicks on Image one item in a list
// this would cause the program to call showImage() for that image only
// note that in this case only image one was loaded into memory
highResolutionImage1.showImage();
// consider using the high resolution image object directly
Image highResolutionImageNoProxy1 = new HighResolutionImage("sample/veryHighResPhoto1.jpeg");
Image highResolutionImageNoProxy2 = new HighResolutionImage("sample/veryHighResPhoto2.jpeg");
Image highResolutionImageBoProxy3 = new HighResolutionImage("sample/veryHighResPhoto3.jpeg");
// assume that the user selects image two item from images list
highResolutionImageNoProxy2.showImage();
// note that in this case all images have been loaded into memory
// and not all have been actually displayed
// this is a waste of memory resources
}
}
Assume proxy pattern is implemented correctly, and this is the main method of the program. Here is what i wonder: The comments in the code say that when we use proxy image objects, if we load a picture into memory, just that image is loaded. But if we do not use proxy and directly create real images, when we load an instance of this class, we load all instances of the class into memory. I do not understand why this is the case. Yes, the whole point of proxy pattern is to do this, but i do not understand why all 3 of the highResolutionImageNoProxy objects are loaded into memory when we call highResolutionImageNoProxy2.showImage(); . Can anyonbody explain it?
Thanks
Edit: I think i figured out why. Because the ImageProxy class calls the constructor of HighResolutionImage class only when it tries to do an operation on the object, but if we create a HighResolutionImage directly, then since its constructor creates the object, all of them are loaded into memory.
The code assumes that when you create an instance of HighResolutionImage, the image is loaded to the memory, even if showImage() isn't called.
The proxy will assure that the image is loaded to the memory only when showImage() is called.
//load veryHighResPhoto1 to memory
Image highResolutionImageNoProxy1 = new HighResolutionImage("sample/veryHighResPhoto1.jpeg");
//load veryHighResPhoto2 to memory
Image highResolutionImageNoProxy2 = new HighResolutionImage("sample/veryHighResPhoto2.jpeg");
//load veryHighResPhoto3 to memory
Image highResolutionImageBoProxy3 = new HighResolutionImage("sample/veryHighResPhoto3.jpeg");
//load just the proxys (image not loaded yet)
Image highResolutionImage1 = new ImageProxy("sample/veryHighResPhoto1.jpeg");
Image highResolutionImage2 = new ImageProxy("sample/veryHighResPhoto2.jpeg");
Image highResolutionImage3 = new ImageProxy("sample/veryHighResPhoto3.jpeg");
//trigger the load of the image into memory
highResolutionImage1.showImage();

ClientBundle don't load the ImageResource

I try to use the ClientBundle implementation to manage my Images to a large File and minimize the HTTP-Requests.
I put in my gwt.xml
Generate the ClientBundle
public interface ResourceBundle extends ClientBundle {
public static final ResourceBundle INSTANCE = GWT.create(ResourceBundle.class);
#Source("tiles/smiley.png")
ImageResource smiley();
}
The Image would be found, no errors.
Here is the code
#Override
public void onModuleLoad() {
CLogger.log("Start Engine");
int width = 800;
int height = 600;
Canvas canvas = Canvas.createIfSupported();
canvas.setWidth(width + "px");
canvas.setHeight(height + "px");
canvas.setCoordinateSpaceWidth(width);
canvas.setCoordinateSpaceHeight(height);
Context2d c = canvas.getContext2d();
Image img = new Image(ResourceBundle.INSTANCE.smiley());
img.addLoadHandler(new LoadHandler() {
#Override
public void onLoad(LoadEvent event) {
CLogger.log(event.getSource() + " loaded");
}
});
CLogger.log("Visible: " + img.isVisible());
c.drawImage((ImageElement) new Image(ResourceBundle.INSTANCE.smiley()).getElement().cast(), 0, 0);
RootPanel.get().add(canvas);
}
I create a simple Canvas and set the size to 800x600. I create a new Context2D Object to draw the Image at the Context and add the Canvas to the RootPanel.
The logs shows:
[20:10:21.676] - Start Engine
[20:10:21.851] - Visible: true
[20:10:21.853] - http://127.0.0.1:8888/engine/7D39451825E9952050F44A6B8E2E15F3.cache.png
The Image exists under the logged URL so everything looks fine. But the Image would not be draw or it would draw but not display.
Anybody an idea?
I thought the ClientBundle loads the Images as the start in the backend. So if I get an Instance every Image/Css and others fill be loaded?
Regars Markus
Image contents aren't guaranteed to be loaded synchronously. Depending on the capabilities of the browser and the size of the image data, the resource may be stored as a standalone file, which appears to be the case that you're describing (i.e. cache.png). Does a formulation like this make any difference?
final Image img = new Image(ResourceBundle.INSTANCE.smiley());
img.addLoadHandler(new LoadHandler() {
public void onLoad(LoadEvent e) {
c.drawImage((ImageElement) img.getElement());
}
}
RootPanel.get().add(img);
If you use CSSResources and ImageBundles outside of UiBinder you have to make sure that the stlyesheet and images are injected properly.
See here for more information.

Categories