ERLEDIGT
JA
JA
ANTWORTEN
6
6
ZUGRIFFE
966
966
EMPFEHLEN
-
Hallo,
ich habe ein minimalistisches Photoalbum geschrieben. Um die Ladezeiten zu verkürzen, arbeitet das Programm mit verkleinerten Abbildern der Originale. Diese Abbilder werden in einem Unterverzeichnis des Programminstallationspfades abgelegt. Inzwischen liegen mehrere tausend dieser verkleinerten Originale in besagtem Unterverzeichnis. Dies wirkt sich leider sehr negativ auf die Arbeitsgeschwindigkeit von Betriebssystem als auch Java aus, sobald auf dieses Unterverzeichnis zugegriffen werden muss.
Daher möchte ich die vielen kleinen Dateien zu einer großen Datei zusammenfassen. Neue Bilder werden einfach ans Ende dieses Archivs gestellt und Startposition und Länge in einer zweiten Datei gesichert.
Das Anhängen soll wie folgt ablaufen:
1. Original lesen
2. Original skalieren und in einem Image Objekt speichern
3. dieses Image Objekt als JPG-Bild ans Ende des Dateiarchivs schreiben
4. Startposition und Größe in ein Inhaltsverzeichnis schreiben
Die Punkte 1, 2 und 4 sind kein Problem. Leider weiß ich nicht, wie ich Punkt 3 realisieren kann, da mir die Grundlagen hierzu fehlen.
Das Auslesen soll wie folgt ablaufen:
1. Dateiarchiv lesend als Random Access File öffnen
2. da Anfangspunkt und Länge des Bildes innerhalb des Archivs bekannt sind, das Bild laden und in einem Image-Objekt ablegen
Punkt 1 dürfte noch zu lösen sein. Aber der zweite Punkte erfordert wieder Wissen, das ich nicht habe und nicht weiß, wo ich es herbekomme.
Über Ratschläge oder Code-Beispiele, die mir bei der Lösung dieses Problems behilflich sind, würde ich mich sehr freuen.
Jabo
-
24.02.07 14:17 #2
- Registriert seit
- Jun 2002
- Ort
- Saarbrücken (Saarland)
- Beiträge
- 9.886
- Blog-Einträge
- 29
Hallo,
schau mal hier:
Code java:1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564
/** * */ package de.tutorials; import java.awt.Dimension; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.Closeable; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FilenameFilter; import java.io.IOException; import java.io.RandomAccessFile; import java.util.Collections; import java.util.HashSet; import java.util.Set; import javax.imageio.ImageIO; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import org.eclipse.jface.text.link.LinkedModeUI.ExitFlags; /** * @author Tom * */ public class ImageIndexExample { /** * @param args */ public static void main(String[] args) throws Exception { File imageDir = new File("C:/TEMP/bubu"); File imageIndex = new File("C:/TEMP/bubu/images.index"); File imageThumbs = new File("C:/TEMP/bubu/images.thumb"); ImageThumbnailIndex imageThumbnailIndex = new ImageThumbnailIndex( imageIndex, imageThumbs); imageThumbnailIndex.open(); imageThumbnailIndex.rebuildIndex(imageDir); displayThumbs(imageThumbnailIndex); } private static void displayThumbs( final ImageThumbnailIndex imageThumbnailIndex) throws Exception { JFrame frm = new JFrame("ImageIndexExample"); frm.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { try { imageThumbnailIndex.close(true); } catch (IOException e1) { e1.printStackTrace(); } System.exit(0); } }); JPanel panel = new JPanel(); panel.setLayout(new GridLayout(imageThumbnailIndex .getValidRecordCount() / 4, 4)); JScrollPane scrollPane = new JScrollPane(panel); scrollPane.setPreferredSize(new Dimension(400, 300)); initComponents(panel, imageThumbnailIndex); frm.add(scrollPane); frm.pack(); frm.setVisible(true); } private static void initComponents(final JPanel panel, final ImageThumbnailIndex imageThumbnailIndex) throws Exception { for (final ImageIndexRecord record : imageThumbnailIndex.getRecordSet()) { if (record.isValid()) { final JButton button = new JButton(new ImageIcon( imageThumbnailIndex.getThumbnailFor(record))); button.setToolTipText(record.getImagePath()); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // try { // imageThumbnailIndex.delete(record); // panel.remove(button); // panel.updateUI(); // } catch (Exception e1) { // e1.printStackTrace(); // } JFrame imageDisplay = new JFrame(record.getImagePath()); imageDisplay.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); imageDisplay.add(new JLabel(new ImageIcon(record.getImagePath()))); imageDisplay.pack(); imageDisplay.setVisible(true); } }); panel.add(button); } } } static class ImageThumbnailIndex implements Closeable { Set<ImageIndexRecord> records; File indexFile; File thumbnailFile; int lastIndexOffset; int lastThumbnailOffset; RandomAccessFile indexRandomAccessFile; FileOutputStream thumbnailOutputStream; RandomAccessFile thumbnailRandomAccess; int validRecordCount; BufferedImage scaledImage; FilenameFilter imageFileNameFilter = new FilenameFilter() { public boolean accept(File dir, String name) { String fileName = name.toLowerCase(); return fileName.endsWith(".jpg") || fileName.endsWith(".jpeg") || fileName.endsWith(".gif") || fileName.endsWith(".png"); } }; public ImageThumbnailIndex(File indexFile, File thumbnailFile) { this.indexFile = indexFile; this.thumbnailFile = thumbnailFile; } void open() throws Exception { if (!indexFile.exists()) { indexFile.createNewFile(); } DataInputStream indexDataInputStream = new DataInputStream( new FileInputStream(indexFile)); while (indexDataInputStream.available() > 0) { int currentThumbnailOffset = indexDataInputStream.readInt(); int currentIndexOffset = indexDataInputStream.readInt(); int code = indexDataInputStream.readInt(); int chars = indexDataInputStream.readInt(); StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < chars; i++) { stringBuilder.append(indexDataInputStream.readChar()); } int imageSize = indexDataInputStream.readInt(); int originalImageSize = indexDataInputStream.readInt(); int originalFileTimeStamp = indexDataInputStream.readInt(); ImageIndexRecord imageIndexRecord = new ImageIndexRecord( currentThumbnailOffset, currentIndexOffset, code, stringBuilder.toString(), imageSize, originalImageSize, originalFileTimeStamp); getRecords().add(imageIndexRecord); if (imageIndexRecord.isValid()) { validRecordCount++; } lastThumbnailOffset += imageSize; } lastIndexOffset = (int) indexFile.length(); indexDataInputStream.close(); } public BufferedImage getThumbnailFor(ImageIndexRecord imageIndexRecord) throws Exception { if (null == thumbnailRandomAccess) { thumbnailRandomAccess = new RandomAccessFile(thumbnailFile, "rw"); } long oldPosition = thumbnailRandomAccess.getFilePointer(); thumbnailRandomAccess.seek(imageIndexRecord.getOffset()); byte[] imageData = new byte[imageIndexRecord.getImageSize()]; thumbnailRandomAccess.read(imageData, 0, imageIndexRecord .getImageSize()); BufferedImage thumbnail = ImageIO.read(new ByteArrayInputStream( imageData)); thumbnailRandomAccess.seek(oldPosition); return thumbnail; } public void rebuildIndex(File imageDirectory) throws Exception { long time = -System.currentTimeMillis(); for (File imageFile : imageDirectory.listFiles(imageFileNameFilter)) { if (!contains(imageFile)) { index(imageFile); } else { ImageIndexRecord imageIndexRecord = getValidImageIndexRecordBy(imageFile); if (null == imageIndexRecord) { ImageIndexRecord deletedImageIndexRecord = getImageIndexRecordBy(imageFile); if (imageFileChanged(imageFile, deletedImageIndexRecord)) { index(imageFile); } } else if (imageFileChanged(imageFile, imageIndexRecord)) { delete(imageIndexRecord); index(imageFile); } } } time += System.currentTimeMillis(); System.out.println("index rebuild took: " + (time / 1000) + "s"); } /** * @param imageFile * @param imageIndexRecord * @return */ private boolean imageFileChanged(File imageFile, ImageIndexRecord imageIndexRecord) { return !sameFileSize(imageFile, imageIndexRecord) && !sameLastModified(imageFile, imageIndexRecord); } private void index(File imageFile) throws Exception { System.out.println("indexing: " + imageFile.getAbsolutePath()); if (null == indexRandomAccessFile) { indexRandomAccessFile = new RandomAccessFile(indexFile, "rw"); } if (null == thumbnailOutputStream) { thumbnailOutputStream = new FileOutputStream(thumbnailFile, true); } indexRandomAccessFile.seek(lastIndexOffset); long indexOffset = indexRandomAccessFile.getFilePointer(); indexRandomAccessFile.writeInt(lastThumbnailOffset); // currentThumbnailOffset indexRandomAccessFile.writeInt((int) indexOffset); indexRandomAccessFile.writeInt(ImageIndexRecord.VALID); // VALID String imageFilePath = imageFile.getAbsolutePath(); indexRandomAccessFile.writeInt(imageFilePath.length()); // char-count indexRandomAccessFile.writeChars(imageFilePath); // chars... BufferedImage image = ImageIO.read(imageFile); getScaledImage().getGraphics() .drawImage(image, 0, 0, 120, 90, null); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); ImageIO.write(scaledImage, "jpeg", byteArrayOutputStream); int originalFileTimeStamp = (int) imageFile.lastModified(); ImageIndexRecord imageIndexRecord = new ImageIndexRecord( lastThumbnailOffset, (int) indexOffset, ImageIndexRecord.VALID, imageFilePath, byteArrayOutputStream.size(), (int) imageFile.length(), originalFileTimeStamp); getRecords().add(imageIndexRecord); lastThumbnailOffset += byteArrayOutputStream.size(); thumbnailOutputStream.write(byteArrayOutputStream.toByteArray()); // imagedata thumbnailOutputStream.flush(); indexRandomAccessFile.writeInt(byteArrayOutputStream.size()); // thumbnail // size indexRandomAccessFile.writeInt((int) imageFile.length()); // original // size indexRandomAccessFile.writeInt(originalFileTimeStamp); lastIndexOffset += (indexRandomAccessFile.getFilePointer() - lastIndexOffset); } private void delete(ImageIndexRecord imageIndexRecord) throws Exception { if (null == indexRandomAccessFile) { indexRandomAccessFile = new RandomAccessFile(indexFile, "rw"); } imageIndexRecord.code = ImageIndexRecord.DELETED; validRecordCount--; int indexOffset = imageIndexRecord.getIndexOffset(); indexRandomAccessFile.seek(indexOffset); indexRandomAccessFile.skipBytes(Integer.SIZE / Byte.SIZE); indexRandomAccessFile.skipBytes(Integer.SIZE / Byte.SIZE); indexRandomAccessFile.writeInt(ImageIndexRecord.DELETED); } private ImageIndexRecord getImageIndexRecordBy(File imageFile) { for (ImageIndexRecord imageIndexRecord : getRecords()) { if (sameFileName(imageFile, imageIndexRecord) && sameFileSize(imageFile, imageIndexRecord) && sameLastModified(imageFile, imageIndexRecord)) { return imageIndexRecord; } } return null; } /** * @param imageFile * @param imageIndexRecord * @return */ private boolean sameLastModified(File imageFile, ImageIndexRecord imageIndexRecord) { return imageIndexRecord.getOriginalFileTimeStamp() == (int) imageFile .lastModified(); } /** * @param imageFile * @param imageIndexRecord * @return */ private boolean sameFileSize(File imageFile, ImageIndexRecord imageIndexRecord) { return imageIndexRecord.getOriginalSize() == (int) imageFile .length(); } /** * @param imageFile * @param imageIndexRecord * @return */ private boolean sameFileName(File imageFile, ImageIndexRecord imageIndexRecord) { return imageIndexRecord.getImagePath().equals(imageFile.getAbsolutePath()); } private ImageIndexRecord getValidImageIndexRecordBy(File imageFile) { ImageIndexRecord imageIndexRecord = getImageIndexRecordBy(imageFile); if (null != imageIndexRecord && imageIndexRecord.isValid()) { return imageIndexRecord; } return null; } public boolean contains(File imageFile) { for (ImageIndexRecord imageIndexRecord : getRecords()) { if (sameFileName(imageFile, imageIndexRecord)) { return true; } } return false; } private Set<ImageIndexRecord> getRecords() { if (null == records) { records = new HashSet<ImageIndexRecord>(128); } return records; } public Set<ImageIndexRecord> getRecordSet() { return Collections.unmodifiableSet(getRecords()); } public void close(boolean compact) throws IOException { if (compact) { compact(); } close(); } private void compact() { // TODO // REMOVE deleted index entries and according thumbnails // ADJUST indexOffsets and according thumbnailOffsets } /** * @return the scaledImage */ public BufferedImage getScaledImage() { if (null == scaledImage) { scaledImage = new BufferedImage(120, 90, BufferedImage.TYPE_INT_RGB); } return scaledImage; } public void close() throws IOException { System.out.println("close"); if (null != this.indexRandomAccessFile) this.indexRandomAccessFile.close(); if (null != this.thumbnailOutputStream) this.thumbnailOutputStream.close(); if (null != this.thumbnailRandomAccess) this.thumbnailRandomAccess.close(); this.records.clear(); this.records = null; this.scaledImage = null; } /** * @return the validRecordCount */ public int getValidRecordCount() { return validRecordCount; } } static class ImageIndexRecord { final static int VALID = 1; final static int DELETED = 2; int offset; int indexOffset; int code; String imagePath; int imageSize; int originalSize; int originalFileTimeStamp; /** * @param offset * @param imageNameLength * @param imagePath * @param imageSize */ public ImageIndexRecord(int offset, int indexOffset, int code, String imagePath, int imageSize, int originalSize, int originalFileTimeStamp) { super(); this.offset = offset; this.indexOffset = indexOffset; this.code = code; this.imagePath = imagePath; this.imageSize = imageSize; this.originalSize = originalSize; this.originalFileTimeStamp = originalFileTimeStamp; } /** * @return the code */ public int getCode() { return code; } /** * @return the offset */ public int getOffset() { return offset; } /** * @return the imageName */ public String getImagePath() { return imagePath; } /** * @return the imageSize */ public int getImageSize() { return imageSize; } /** * @return the originalSize */ public int getOriginalSize() { return originalSize; } public boolean isDeleted() { return getCode() == DELETED; } public boolean isValid() { return getCode() == VALID; } /** * @return the indexOffset */ public int getIndexOffset() { return indexOffset; } /** * @return the originalFileTimeStamp */ public int getOriginalFileTimeStamp() { return originalFileTimeStamp; } /* * (non-Javadoc) * * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((imagePath == null) ? 0 : imagePath.hashCode()); result = prime * result + originalFileTimeStamp; result = prime * result + originalSize; return result; } /* * (non-Javadoc) * * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final ImageIndexRecord other = (ImageIndexRecord) obj; if (imagePath == null) { if (other.imagePath != null) return false; } else if (!imagePath.equals(other.imagePath)) return false; if (originalFileTimeStamp != other.originalFileTimeStamp) return false; if (originalSize != other.originalSize) return false; return true; } @Override public String toString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("Image="); stringBuilder.append(imagePath); stringBuilder.append(" IndexOffset="); stringBuilder.append(indexOffset); stringBuilder.append(" ThumbOffset="); stringBuilder.append(offset); stringBuilder.append(" code="); stringBuilder.append(code == VALID ? "VALID" : "DELETED"); stringBuilder.append(" ThumbSize="); stringBuilder.append(imageSize); stringBuilder.append(" OriginalSize="); stringBuilder.append(originalSize); stringBuilder.append(" OriginalFileTimeStamp="); stringBuilder.append(originalFileTimeStamp); return stringBuilder.toString(); } } }
Die Beispielbilder gibts im Anhang.
Für 97 Bilder mit jeweils ~ 2.1 MB ~ 199 MB ist das erzeugte
images.index File 5 kbyte und das images.thumb 417kbyte groß.
Die Thumbnails liegen dabei als 120x90 Pixel vor.
Das Erzeugen des Indexes dauert dabei 33 Sekunden. Die Aktion die dabei am längsten Dauert ist die Erzeugung der Thumbnails.
Gruß TomJava rocks!
How to become a good Java Programmer?
Does IT in Java and .Net
The only valid measurement of code quality: WTFs / minute
Blog
Xing
Twitter
-
Da sag ich wohl zunächst einmal danke. Sobald es mir gelingt, dass Programm zum Laufen zu bekommen, werde ich mich nochmal melden. Kann aber ein wenig dauern. Da sind doch einige Lücken zu stopfen.
Jabo
-
Nochmals danke für den Programmcode, Tom. Leider ist es mir bislang nicht gelungen, die Qualität der Thumbnails zu verbessern, ohne dabei sehr viel Zeit zu verlieren.
Dein Programm benötigt für meine 300 Testbilder ungefähr 20 Sekunden. Passe ich deinen Code an, stimmt zwar hinterher die Qualität der Vorschaubilder, aber es dauert weit über 200 Sekunden, was eindeutig zu lang ist.
In meinem alten Programm habe ich die Qualität der Vorschaubilder wie folgt verbessert:
Mit JPEGImageWriteParam konnte ich die Qualtität beim Schreiben der Datei beeinflussen.Code :1
scaledimage = orgimage.getScaledInstance(breite,hoehe,orgimage.[B]SCALE_SMOOTH[/B]);
Was mir also noch fehlt, ist eine Möglichkeit, die Qualität der Vorschaubilder zu beeinflussen, ohne dabei viel Zeit zu verlieren - Faktor 10 ist einfach zu lang. Auch möchte ich wieder die Qualität beim Schreiben der JPG-Dateien beeinflussen können.
Vielleicht ist jemand in der Lage, den Programmcode von Tom entsprechend anzupassen.
Jabo
-
06.03.07 14:56 #5
- Registriert seit
- Jun 2002
- Ort
- Saarbrücken (Saarland)
- Beiträge
- 9.886
- Blog-Einträge
- 29
Hallo,
hiermit sollte es im besten Fall doppelt so "flott" gehen:
Code java:1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568
/** * */ package de.tutorials; import java.awt.Dimension; import java.awt.Graphics2D; import java.awt.GridLayout; import java.awt.RenderingHints; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.Closeable; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FilenameFilter; import java.io.IOException; import java.io.RandomAccessFile; import java.util.Collections; import java.util.HashSet; import java.util.Set; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import sun.awt.image.codec.JPEGImageDecoderImpl; import sun.awt.image.codec.JPEGImageEncoderImpl; /** * @author Tom * */ public class ImageIndexExample { /** * @param args */ public static void main(String[] args) throws Exception { File imageDir = new File("d:/dacos portraits"); File imageIndex = new File("d:/dacos portraits/images.index"); File imageThumbs = new File("d:/dacos portraits/images.thumb"); ImageThumbnailIndex imageThumbnailIndex = new ImageThumbnailIndex( imageIndex, imageThumbs); imageThumbnailIndex.open(); imageThumbnailIndex.rebuildIndex(imageDir); displayThumbs(imageThumbnailIndex); } private static void displayThumbs( final ImageThumbnailIndex imageThumbnailIndex) throws Exception { JFrame frm = new JFrame("ImageIndexExample"); frm.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { try { imageThumbnailIndex.close(true); } catch (IOException e1) { e1.printStackTrace(); } System.exit(0); } }); JPanel panel = new JPanel(); panel.setLayout(new GridLayout(imageThumbnailIndex .getValidRecordCount() / 4, 4)); JScrollPane scrollPane = new JScrollPane(panel); scrollPane.setPreferredSize(new Dimension(400, 300)); initComponents(panel, imageThumbnailIndex); frm.add(scrollPane); frm.pack(); frm.setVisible(true); } private static void initComponents(final JPanel panel, final ImageThumbnailIndex imageThumbnailIndex) throws Exception { for (final ImageIndexRecord record : imageThumbnailIndex.getRecordSet()) { if (record.isValid()) { final JButton button = new JButton(new ImageIcon( imageThumbnailIndex.getThumbnailFor(record))); button.setToolTipText(record.getImageName()); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { imageThumbnailIndex.delete(record); panel.remove(button); panel.updateUI(); } catch (Exception e1) { e1.printStackTrace(); } } }); panel.add(button); } } } static class ImageThumbnailIndex implements Closeable { Set<ImageIndexRecord> records; File indexFile; File thumbnailFile; int lastIndexOffset; int lastThumbnailOffset; RandomAccessFile indexRandomAccessFile; FileOutputStream thumbnailOutputStream; RandomAccessFile thumbnailRandomAccess; int validRecordCount; BufferedImage scaledImage; FilenameFilter imageFileNameFilter = new FilenameFilter() { public boolean accept(File dir, String name) { String fileName = name.toLowerCase(); return fileName.endsWith(".jpg") || fileName.endsWith(".jpeg") || fileName.endsWith(".gif") || fileName.endsWith(".png"); } }; public ImageThumbnailIndex(File indexFile, File thumbnailFile) { this.indexFile = indexFile; this.thumbnailFile = thumbnailFile; } public void open() throws Exception { if (!indexFile.exists()) { indexFile.createNewFile(); } DataInputStream indexDataInputStream = new DataInputStream( new FileInputStream(indexFile)); while (indexDataInputStream.available() > 0) { int currentThumbnailOffset = indexDataInputStream.readInt(); int currentIndexOffset = indexDataInputStream.readInt(); int code = indexDataInputStream.readInt(); int chars = indexDataInputStream.readInt(); StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < chars; i++) { stringBuilder.append(indexDataInputStream.readChar()); } int imageSize = indexDataInputStream.readInt(); int originalImageSize = indexDataInputStream.readInt(); int originalFileTimeStamp = indexDataInputStream.readInt(); ImageIndexRecord imageIndexRecord = new ImageIndexRecord( currentThumbnailOffset, currentIndexOffset, code, stringBuilder.toString(), imageSize, originalImageSize, originalFileTimeStamp); getRecords().add(imageIndexRecord); if (imageIndexRecord.isValid()) { validRecordCount++; } lastThumbnailOffset += imageSize; } lastIndexOffset = (int) indexFile.length(); indexDataInputStream.close(); } public BufferedImage getThumbnailFor(ImageIndexRecord imageIndexRecord) throws Exception { if (null == thumbnailRandomAccess) { thumbnailRandomAccess = new RandomAccessFile(thumbnailFile, "rw"); } long oldPosition = thumbnailRandomAccess.getFilePointer(); thumbnailRandomAccess.seek(imageIndexRecord.getOffset()); byte[] imageData = new byte[imageIndexRecord.getImageSize()]; thumbnailRandomAccess.read(imageData, 0, imageIndexRecord .getImageSize()); BufferedImage thumbnail = new JPEGImageDecoderImpl( new ByteArrayInputStream(imageData)) .decodeAsBufferedImage(); thumbnailRandomAccess.seek(oldPosition); return thumbnail; } public void rebuildIndex(File imageDirectory) throws Exception { long time = -System.currentTimeMillis(); for (File imageFile : imageDirectory.listFiles(imageFileNameFilter)) { if (!contains(imageFile)) { index(imageFile); } else { ImageIndexRecord imageIndexRecord = getValidImageIndexRecordBy(imageFile); if (null == imageIndexRecord) { ImageIndexRecord deletedImageIndexRecord = getImageIndexRecordBy(imageFile); if (imageFileChanged(imageFile, deletedImageIndexRecord)) { index(imageFile); } } else if (imageFileChanged(imageFile, imageIndexRecord)) { delete(imageIndexRecord); index(imageFile); } } } time += System.currentTimeMillis(); System.out.println("index rebuild took: " + (time / 1000) + "s"); } /** * @param imageFile * @param imageIndexRecord * @return */ private boolean imageFileChanged(File imageFile, ImageIndexRecord imageIndexRecord) { return !sameFileSize(imageFile, imageIndexRecord) && !sameLastModified(imageFile, imageIndexRecord); } private void index(File imageFile) throws Exception { System.out.println("indexing: " + imageFile.getAbsolutePath()); if (null == indexRandomAccessFile) { indexRandomAccessFile = new RandomAccessFile(indexFile, "rw"); } if (null == thumbnailOutputStream) { thumbnailOutputStream = new FileOutputStream(thumbnailFile, true); } indexRandomAccessFile.seek(lastIndexOffset); long indexOffset = indexRandomAccessFile.getFilePointer(); indexRandomAccessFile.writeInt(lastThumbnailOffset); // currentThumbnailOffset indexRandomAccessFile.writeInt((int) indexOffset); indexRandomAccessFile.writeInt(ImageIndexRecord.VALID); // VALID String imageFileName = imageFile.getName(); indexRandomAccessFile.writeInt(imageFileName.length()); // char-count indexRandomAccessFile.writeChars(imageFileName); // chars... BufferedImage image = new JPEGImageDecoderImpl(new FileInputStream( imageFile)).decodeAsBufferedImage(); getScaledImage().getGraphics() .drawImage(image, 0, 0, 120, 90, null); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); new JPEGImageEncoderImpl(byteArrayOutputStream).encode(scaledImage); int originalFileTimeStamp = (int) imageFile.lastModified(); ImageIndexRecord imageIndexRecord = new ImageIndexRecord( lastThumbnailOffset, (int) indexOffset, ImageIndexRecord.VALID, imageFileName, byteArrayOutputStream.size(), (int) imageFile.length(), originalFileTimeStamp); getRecords().add(imageIndexRecord); lastThumbnailOffset += byteArrayOutputStream.size(); thumbnailOutputStream.write(byteArrayOutputStream.toByteArray()); // imagedata thumbnailOutputStream.flush(); indexRandomAccessFile.writeInt(byteArrayOutputStream.size()); // thumbnail // size indexRandomAccessFile.writeInt((int) imageFile.length()); // original // size indexRandomAccessFile.writeInt(originalFileTimeStamp); lastIndexOffset += (indexRandomAccessFile.getFilePointer() - lastIndexOffset); } private void delete(ImageIndexRecord imageIndexRecord) throws Exception { if (null == indexRandomAccessFile) { indexRandomAccessFile = new RandomAccessFile(indexFile, "rw"); } imageIndexRecord.code = ImageIndexRecord.DELETED; validRecordCount--; int indexOffset = imageIndexRecord.getIndexOffset(); indexRandomAccessFile.seek(indexOffset); indexRandomAccessFile.skipBytes(Integer.SIZE / Byte.SIZE); indexRandomAccessFile.skipBytes(Integer.SIZE / Byte.SIZE); indexRandomAccessFile.writeInt(ImageIndexRecord.DELETED); } private ImageIndexRecord getImageIndexRecordBy(File imageFile) { for (ImageIndexRecord imageIndexRecord : getRecords()) { if (sameFileName(imageFile, imageIndexRecord) && sameFileSize(imageFile, imageIndexRecord) && sameLastModified(imageFile, imageIndexRecord)) { return imageIndexRecord; } } return null; } /** * @param imageFile * @param imageIndexRecord * @return */ private boolean sameLastModified(File imageFile, ImageIndexRecord imageIndexRecord) { return imageIndexRecord.getOriginalFileTimeStamp() == (int) imageFile .lastModified(); } /** * @param imageFile * @param imageIndexRecord * @return */ private boolean sameFileSize(File imageFile, ImageIndexRecord imageIndexRecord) { return imageIndexRecord.getOriginalSize() == (int) imageFile .length(); } /** * @param imageFile * @param imageIndexRecord * @return */ private boolean sameFileName(File imageFile, ImageIndexRecord imageIndexRecord) { return imageIndexRecord.getImageName().equals(imageFile.getName()); } private ImageIndexRecord getValidImageIndexRecordBy(File imageFile) { ImageIndexRecord imageIndexRecord = getImageIndexRecordBy(imageFile); if (null != imageIndexRecord && imageIndexRecord.isValid()) { return imageIndexRecord; } return null; } public boolean contains(File imageFile) { for (ImageIndexRecord imageIndexRecord : getRecords()) { if (sameFileName(imageFile, imageIndexRecord)) { return true; } } return false; } private Set<ImageIndexRecord> getRecords() { if (null == records) { records = new HashSet<ImageIndexRecord>(128); } return records; } public Set<ImageIndexRecord> getRecordSet() { return Collections.unmodifiableSet(getRecords()); } public void close(boolean compact) throws IOException { if (compact) { compact(); } close(); } private void compact() { // TODO // REMOVE deleted index entries and according thumbnails // ADJUST indexOffsets and according thumbnailOffsets } /** * @return the scaledImage */ public BufferedImage getScaledImage() { if (null == scaledImage) { scaledImage = new BufferedImage(120, 90, BufferedImage.TYPE_INT_RGB); ((Graphics2D) scaledImage.getGraphics()).setRenderingHint( RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); } return scaledImage; } public void close() throws IOException { System.out.println("close"); if (null != this.indexRandomAccessFile) this.indexRandomAccessFile.close(); if (null != this.thumbnailOutputStream) this.thumbnailOutputStream.close(); if (null != this.thumbnailRandomAccess) this.thumbnailRandomAccess.close(); this.records.clear(); this.records = null; this.scaledImage = null; } /** * @return the validRecordCount */ public int getValidRecordCount() { return validRecordCount; } } static class ImageIndexRecord { final static int VALID = 1; final static int DELETED = 2; int offset; int indexOffset; int code; String imageName; int imageSize; int originalSize; int originalFileTimeStamp; /** * @param offset * @param imageNameLength * @param imageName * @param imageSize */ public ImageIndexRecord(int offset, int indexOffset, int code, String imageName, int imageSize, int originalSize, int originalFileTimeStamp) { super(); this.offset = offset; this.indexOffset = indexOffset; this.code = code; this.imageName = imageName; this.imageSize = imageSize; this.originalSize = originalSize; this.originalFileTimeStamp = originalFileTimeStamp; } /** * @return the code */ public int getCode() { return code; } /** * @return the offset */ public int getOffset() { return offset; } /** * @return the imageName */ public String getImageName() { return imageName; } /** * @return the imageSize */ public int getImageSize() { return imageSize; } /** * @return the originalSize */ public int getOriginalSize() { return originalSize; } public boolean isDeleted() { return getCode() == DELETED; } public boolean isValid() { return getCode() == VALID; } /** * @return the indexOffset */ public int getIndexOffset() { return indexOffset; } /** * @return the originalFileTimeStamp */ public int getOriginalFileTimeStamp() { return originalFileTimeStamp; } /* * (non-Javadoc) * * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((imageName == null) ? 0 : imageName.hashCode()); result = prime * result + originalFileTimeStamp; result = prime * result + originalSize; return result; } /* * (non-Javadoc) * * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final ImageIndexRecord other = (ImageIndexRecord) obj; if (imageName == null) { if (other.imageName != null) return false; } else if (!imageName.equals(other.imageName)) return false; if (originalFileTimeStamp != other.originalFileTimeStamp) return false; if (originalSize != other.originalSize) return false; return true; } @Override public String toString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("Image="); stringBuilder.append(imageName); stringBuilder.append(" IndexOffset="); stringBuilder.append(indexOffset); stringBuilder.append(" ThumbOffset="); stringBuilder.append(offset); stringBuilder.append(" code="); stringBuilder.append(code == VALID ? "VALID" : "DELETED"); stringBuilder.append(" ThumbSize="); stringBuilder.append(imageSize); stringBuilder.append(" OriginalSize="); stringBuilder.append(originalSize); stringBuilder.append(" OriginalFileTimeStamp="); stringBuilder.append(originalFileTimeStamp); return stringBuilder.toString(); } } }
Gruß TomJava rocks!
How to become a good Java Programmer?
Does IT in Java and .Net
The only valid measurement of code quality: WTFs / minute
Blog
Xing
Twitter
-
Bin mit den Programmänderungen gut voran gekommen. Zeigen möchte ich die Methode, mit der die Bilder skaliert werden. Diese Methode ist im Programm selbst in einer Schleife eingebettet, falls mehrere Bilder verarbeitet werden müssen.
Die wichtigsten Schritte sind mit Kommentaren versehen. Würde mich über den ein oder anderen Kommentar freuen - egal ob positiv oder negativ. Vielleicht lässt sich ja noch etwas verbessern.
Code :1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
public void BildSkalieren(String quelldatei, String zieldatei, int thumbgr) { int breite = 0; int hoehe = 0; long dateiBeginn = 0; long dateiLaenge = 0; //Anmerkung: //quelldatei = Pfad und Dateiname des Bildes, von dem ein Thumbnail erzeugt werden soll //zieldatei = Pfad und Dateiname des Dateiarchivs ohne Dateierweiterung //thumbgr = maximale Breite und maximale Hoehe eines Thumbnail // //Ablauf: //1. Bild laden, Seitelaengen bestimmen, neue Seitenlaengen berechnen //2. BufferedImage nach BufferedImage (inkl. HQ-Skalierung beim Uebertraegen //3. skaliertes Bild ans Ende des Dateiarchivs anhaengen //4. Index des Dateiarchiv aktualisieren //5. Aufraemen (gibt belegten Speicher wieder frei, der sonst von der GC ignoriert wuerde) try { //1. //Bild laden BufferedImage orgimg = ImageIO.read(new File(quelldatei)); //Seitenlaengen bestimmen breite = orgimg.getWidth(null); hoehe = orgimg.getHeight(null); //neue Seitenlaengen berechnen if (breite>hoehe) { hoehe = thumbgr*hoehe/breite; breite = thumbgr; } else if (breite<hoehe) { breite = thumbgr*breite/hoehe; hoehe = thumbgr; } else { breite = thumbgr; hoehe = thumbgr; } //2. BufferedImage nach BufferedImage (inkl. HQ-Skalierung beim Uebertraegen) BufferedImage outimg = new BufferedImage(breite, hoehe, BufferedImage.TYPE_INT_RGB); Graphics2D graphics2D = outimg.createGraphics(); //graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR); //graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); graphics2D.drawImage(orgimg, 0, 0, breite, hoehe, null); graphics2D.dispose(); //3. skaliertes Bild ans Ende des Dateiarchivs anhaengen ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); //Qualitätstufe beim Schreiben des Thumbnail bestimmen Iterator iterator = ImageIO.getImageWritersBySuffix("jpeg"); JPEGImageWriteParam imageWriteParam = new JPEGImageWriteParam(Locale.getDefault()); imageWriteParam.setCompressionMode(JPEGImageWriteParam.MODE_EXPLICIT); imageWriteParam.setCompressionQuality(1.0F); //imgout nach byteArrayOutputStream IIOImage iioImage = new IIOImage(outimg, null, null); ImageWriter imageWriter = (ImageWriter) iterator.next(); imageWriter.setOutput(ImageIO.createImageOutputStream(byteArrayOutputStream)); imageWriter.write(null, iioImage, imageWriteParam); imageWriter.dispose(); try { FileOutputStream thumbnailOutputStream = new FileOutputStream(new File(zieldatei+".dat"),true); dateiBeginn = thumbnailOutputStream.getChannel().size(); thumbnailOutputStream.write(byteArrayOutputStream.toByteArray()); // imagedata dateiLaenge = byteArrayOutputStream.size(); thumbnailOutputStream.flush(); thumbnailOutputStream.close(); } catch (Exception error) { System.out.println("Fehler beim Schreiben von ./alben/album2/archiv2.dat"); } //4. Index des Dateiarchiv aktualisieren try { String str; File fin = new File(zieldatei+".idx"); File fot = new File(zieldatei+".tmp"); BufferedWriter ot = new BufferedWriter(new FileWriter(zieldatei+".tmp")); int eintraege = 1; if (fin.exists()) { BufferedReader in = new BufferedReader(new FileReader(zieldatei+".idx")); str = in.readLine(); eintraege = eintraege+Integer.parseInt(str); str = Integer.toString(eintraege); ot.write(str); while ((str = in.readLine()) != null) { ot.newLine(); ot.write(str); } in.close(); fin.delete(); } else { str = Integer.toString(eintraege); ot.write(str); } ot.newLine(); ot.write(quelldatei); ot.newLine(); ot.write(Long.toString(dateiBeginn)); ot.newLine(); ot.write(Long.toString(dateiLaenge)); ot.newLine(); ot.close(); fot.renameTo(fin); } catch (IOException error) { System.out.println("Probleme bei Schreiben des Index: "+error); } //5. Aufraemen (gibt belegten Speicher wieder frei, der sonst von der GC ignoriert wuerde) orgimg.flush(); outimg.flush(); } catch (IOException error) { System.out.println(quelldatei+" konnte nicht geladen werden!"); } }
-
Aktuell bereitet mir Punkt 4 im Code vom vorigen Post Probleme. Es kommt immer wieder vor, dass die renameTo()-Methode oder aber die delete()-Methode der Klasse File nicht fehlerfrei durchlaufen. Fast so, als wird die Index-Datei beim Versuch von irgendeinem anderen Prozess blockiert.
Interessant hierbei ist die Tatsache, dass dieses Problem ausschließlich dann auftritt, wenn ich die Parameter für die Heap Size (z.B. -Xms64m -Xmx80m) setze.
Kann mir dieses Verhalten jemand erklären?
Jabo
Edit: Die Datei wurde an anderer Stelle im Programm geöffnet, aber nicht wieder geschlossen. Ist jetzt behoben und alles läuft.Geändert von jabonva (27.03.07 um 20:04 Uhr)
Ähnliche Themen
-
Überprüfung einer Datei ob diese schon inder der Datenbank vorhanden ist ..
Von Ikkunaprincessa im Forum PHPAntworten: 13Letzter Beitrag: 05.12.08, 20:10 -
Css Datei anhängen
Von byronic im Forum Javascript & AjaxAntworten: 2Letzter Beitrag: 31.12.07, 14:47 -
ID mit PHP einer Seite/Datei zuweisen/anhängen
Von Ingolo im Forum PHPAntworten: 9Letzter Beitrag: 31.05.06, 14:14 -
Wie kann ich diese html Datei auslesen?
Von speicher im Forum PHPAntworten: 3Letzter Beitrag: 08.01.05, 19:09 -
auslesen einer XML Datei via PHP
Von virtualsix im Forum PHPAntworten: 7Letzter Beitrag: 13.10.04, 18:32





Zitieren

Login





