hw3: PhotoAlbumView: improve performance by caching thumbnails

This commit is contained in:
Yuri Tatishchev 2025-03-25 00:47:27 -07:00
parent d4705dc11e
commit c10ba4b2fc
Signed by: CaZzzer
GPG Key ID: E0EBF441EA424369

View File

@ -6,7 +6,9 @@ import model.PhotoAlbumModel;
import javax.swing.*;
import java.awt.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class PhotoAlbumView extends JFrame implements PhotoAlbumModel.ModelChangeListener {
private PhotoAlbumModel model;
@ -143,6 +145,8 @@ public class PhotoAlbumView extends JFrame implements PhotoAlbumModel.ModelChang
private final JLabel textLabel = new JLabel();
private final JLabel detailsLabel = new JLabel();
private final Map<String, ImageIcon> thumbnailCache = new HashMap<>();
public PhotoListCellRenderer() {
setLayout(new BorderLayout(5, 0));
@ -170,7 +174,8 @@ public class PhotoAlbumView extends JFrame implements PhotoAlbumModel.ModelChang
textLabel.setText(name);
Photo photo = model.getPhotos().get(index);
ImageIcon thumbnail = loadThumbnail(photo.filePath());
ImageIcon thumbnail = thumbnailCache.computeIfAbsent(photo.filePath(), this::loadThumbnail);
// ImageIcon thumbnail = loadThumbnail(photo.filePath());
imageLabel.setIcon(thumbnail);
// Format date
@ -181,24 +186,24 @@ public class PhotoAlbumView extends JFrame implements PhotoAlbumModel.ModelChang
return this;
}
}
private String formatFileSize(long size) {
if (size < 1024 * 1024) {
return String.format("%.1f KB", size / 1024.0);
} else {
return String.format("%.1f MB", size / (1024.0 * 1024));
private String formatFileSize(long size) {
if (size < 1024 * 1024) {
return String.format("%.1f KB", size / 1024.0);
} else {
return String.format("%.1f MB", size / (1024.0 * 1024));
}
}
}
private ImageIcon loadThumbnail(String path) {
try {
ImageIcon icon = new ImageIcon(path);
Image img = icon.getImage();
Image scaledImg = img.getScaledInstance(50, 50, Image.SCALE_AREA_AVERAGING);
return new ImageIcon(scaledImg);
} catch (Exception e) {
return null;
private ImageIcon loadThumbnail(String path) {
try {
ImageIcon icon = new ImageIcon(path);
Image img = icon.getImage();
Image scaledImg = img.getScaledInstance(50, 50, Image.SCALE_AREA_AVERAGING);
return new ImageIcon(scaledImg);
} catch (Exception e) {
return null;
}
}
}
}