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 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463
|
package ij.io;
import ij.*;
import ij.gui.*;
import ij.process.*;
import ij.plugin.frame.*;
import ij.plugin.*;
import ij.text.TextWindow;
import ij.util.Java2;
import ij.measure.ResultsTable;
import ij.macro.Interpreter;
import ij.util.Tools;
import java.awt.*;
import java.awt.image.*;
import java.io.*;
import java.net.URL;
import java.net.*;
import java.util.*;
import java.util.zip.*;
import javax.swing.*;
import javax.swing.filechooser.*;
import java.awt.event.KeyEvent;
import javax.imageio.ImageIO;
import java.lang.reflect.Method;
/** Opens tiff (and tiff stacks), dicom, fits, pgm, jpeg, bmp or
gif images, and look-up tables, using a file open dialog or a path.
Calls HandleExtraFileTypes plugin if the file type is unrecognised. */
public class Opener {
public static final int UNKNOWN=0,TIFF=1,DICOM=2,FITS=3,PGM=4,JPEG=5,
GIF=6,LUT=7,BMP=8,ZIP=9,JAVA_OR_TEXT=10,ROI=11,TEXT=12,PNG=13,
TIFF_AND_DICOM=14,CUSTOM=15, AVI=16, OJJ=17, TABLE=18, RAW=19; // don't forget to also update 'types'
public static final String[] types = {"unknown","tif","dcm","fits","pgm",
"jpg","gif","lut","bmp","zip","java/txt","roi","txt","png","t&d","custom","ojj","table","raw"};
private static String defaultDirectory = null;
private int fileType;
private boolean error;
private boolean isRGB48;
private boolean silentMode;
private String omDirectory;
private File[] omFiles;
private static boolean openUsingPlugins;
private static boolean bioformats;
private String url;
private boolean useHandleExtraFileTypes;
static {
Hashtable commands = Menus.getCommands();
bioformats = commands!=null && commands.get("Bio-Formats Importer")!=null;
}
public Opener() {
}
/**
* Displays a file open dialog box and then opens the tiff, dicom,
* fits, pgm, jpeg, bmp, gif, lut, roi, or text file selected by
* the user. Displays an error message if the selected file is not
* in a supported format. This is the method that
* ImageJ's File/Open command uses to open files.
* @see ij.IJ#open
* @see ij.IJ#open(String)
* @see ij.IJ#openImage
* @see ij.IJ#openImage(String)
*/
public void open() {
OpenDialog od = new OpenDialog("Open", "");
String directory = od.getDirectory();
String name = od.getFileName();
if (name!=null) {
String path = directory+name;
error = false;
open(path);
if (!error) Menus.addOpenRecentItem(path);
}
}
/**
* Opens and displays the specified tiff, dicom, fits, pgm, jpeg,
* bmp, gif, lut, roi, or text file. Displays an error message if
* the file is not in a supported format.
* @see ij.IJ#open(String)
* @see ij.IJ#openImage(String)
*/
public void open(String path) {
boolean isURL = path.contains("://") || path.contains("file:/");
if (isURL && isText(path)) {
openTextURL(path);
return;
}
if (path.endsWith(".jar") || path.endsWith(".class")) {
(new PluginInstaller()).install(path);
return;
}
path = makeFullPath(path);
if (!silentMode)
IJ.showStatus("Opening: " + path);
long start = System.currentTimeMillis();
ImagePlus imp = null;
if (path.endsWith(".txt"))
this.fileType = JAVA_OR_TEXT;
else {
useHandleExtraFileTypes = true;
imp = openImage(path);
}
if (imp==null && isURL)
return;
if (imp!=null) {
WindowManager.checkForDuplicateName = true;
if (isRGB48)
openRGB48(imp);
else
imp.show(getLoadRate(start,imp));
} else {
switch (this.fileType) {
case LUT:
imp = (ImagePlus)IJ.runPlugIn("ij.plugin.LutLoader", path);
if (imp.getWidth()!=0)
imp.show();
break;
case ROI:
IJ.runPlugIn("ij.plugin.RoiReader", path);
break;
case JAVA_OR_TEXT: case TEXT:
if (IJ.altKeyDown()) { // open in TextWindow if alt key down
new TextWindow(path,400,450);
IJ.setKeyUp(KeyEvent.VK_ALT);
break;
}
File file = new File(path);
int maxSize = 250000;
long size = file.length();
if (size>=28000) {
String osName = System.getProperty("os.name");
if (osName.equals("Windows 95") || osName.equals("Windows 98") || osName.equals("Windows Me"))
maxSize = 60000;
}
if (size<maxSize) {
Editor ed = new Editor(path);
if (ed!=null) ed.open(getDir(path), getName(path));
} else
new TextWindow(path,400,450);
break;
case OJJ: // ObjectJ project
IJ.runPlugIn("ObjectJ_", path);
break;
case TABLE:
openTable(path);
break;
case RAW:
IJ.runPlugIn("ij.plugin.Raw", path);
break;
case UNKNOWN:
File f = new File(path);
String msg = (f.exists()) ?
"Format not supported or reader plugin not found:"
: "File not found:";
if (path!=null) {
if (path.length()>64)
path = (new File(path)).getName();
if (path.length()<=64)
msg += " \n"+path;
}
if (openUsingPlugins && msg.length()>20)
msg += "\n \nNOTE: The \"OpenUsingPlugins\" option is set.";
IJ.wait(IJ.isMacro()?500:100); // work around for OS X thread deadlock problem
IJ.error("Opener", msg);
error = true;
break;
}
}
}
/** Displays a JFileChooser and then opens the tiff, dicom,
fits, pgm, jpeg, bmp, gif, lut, roi, or text files selected by
the user. Displays error messages if one or more of the selected
files is not in one of the supported formats. This is the method
that ImageJ's File/Open command uses to open files if
"Open/Save Using JFileChooser" is checked in EditOptions/Misc. */
public void openMultiple() {
LookAndFeel saveLookAndFeel = Java2.getLookAndFeel();
Java2.setSystemLookAndFeel();
// run JFileChooser in a separate thread to avoid possible thread deadlocks
try {
EventQueue.invokeAndWait(new Runnable() {
public void run() {
JFileChooser fc = new JFileChooser();
fc.setMultiSelectionEnabled(true);
fc.setDragEnabled(true);
fc.setTransferHandler(new DragAndDropHandler(fc));
File dir = null;
String sdir = OpenDialog.getDefaultDirectory();
if (sdir!=null)
dir = new File(sdir);
if (dir!=null)
fc.setCurrentDirectory(dir);
if (IJ.debugMode) IJ.log("Opener.openMultiple: "+sdir+" "+dir);
int returnVal = fc.showOpenDialog(IJ.getInstance());
if (returnVal!=JFileChooser.APPROVE_OPTION)
return;
omFiles = fc.getSelectedFiles();
if (omFiles.length==0) { // getSelectedFiles does not work on some JVMs
omFiles = new File[1];
omFiles[0] = fc.getSelectedFile();
}
omDirectory = fc.getCurrentDirectory().getPath()+File.separator;
}
});
} catch (Exception e) {}
if (omDirectory==null) return;
OpenDialog.setDefaultDirectory(omDirectory);
for (int i=0; i<omFiles.length; i++) {
String path = omDirectory + omFiles[i].getName();
open(path);
if (i==0 && Recorder.record)
Recorder.recordPath("open", path);
if (i==0 && !error)
Menus.addOpenRecentItem(path);
}
Java2.setLookAndFeel(saveLookAndFeel);
}
/**
* Opens, but does not display, the specified image file
* and returns an ImagePlus object object if successful,
* or returns null if the file is not in a supported format
* or is not found. Displays a file open dialog if 'path'
* is null or an empty string.
* @see ij.IJ#openImage(String)
* @see ij.IJ#openImage
* @see #openUsingBioFormats
*/
public ImagePlus openImage(String path) {
if (path==null || path.equals(""))
path = getPath();
if (path==null) return null;
ImagePlus img = null;
if (path.contains("://") || path.contains("file:/")) // path is a URL
img = openURL(path);
else
img = openImage(getDir(path), getName(path));
return img;
}
/**
* Open the nth image of the specified tiff stack.
* @see ij.IJ#openImage(String,int)
*/
public ImagePlus openImage(String path, int n) {
if (path==null || path.equals(""))
path = getPath();
if (path==null) return null;
int type = getFileType(path);
if (type!=TIFF)
throw new IllegalArgumentException("Opener: TIFF file required");
return openTiff(path, n);
}
public static String getLoadRate(double time, ImagePlus imp) {
time = (System.currentTimeMillis()-time)/1000.0;
double mb = imp.getWidth()*imp.getHeight()*imp.getStackSize();
int bits = imp.getBitDepth();
if (bits==16)
mb *= 2;
else if (bits==24 || bits==32)
mb *=4;
mb /= 1024*1024;
double rate = mb/time;
int digits = rate<100.0?1:0;
return ""+IJ.d2s(time,2)+" seconds ("+IJ.d2s(mb/time,digits)+" MB/sec)";
}
public static String makeFullPath(String path) {
if (path==null)
return path;
if (!isFullPath(path)) {
String defaultDir = OpenDialog.getDefaultDirectory();
if (defaultDir!=null)
path = defaultDir + path;
else
path = (new File(path)).getAbsolutePath();
}
return path;
}
public static boolean isFullPath(String path) {
if (path==null)
return false;
else
return path.startsWith("/") || path.startsWith("\\") || path.contains(":\\") || path.contains(":/") || path.contains("://");
}
private boolean isText(String path) {
if (path.endsWith(".txt") || path.endsWith(".ijm") || path.endsWith(".java")
|| path.endsWith(".js") || path.endsWith(".html") || path.endsWith(".htm")
|| path.endsWith(".bsh") || path.endsWith(".py") || path.endsWith("/"))
return true;
int lastSlash = path.lastIndexOf("/");
if (lastSlash==-1) lastSlash = 0;
int lastDot = path.lastIndexOf(".");
if (lastDot==-1 || lastDot<lastSlash || (path.length()-lastDot)>6)
return true; // no extension
else
return false;
}
/** Opens the specified file and adds it to the File/Open Recent menu.
Returns true if the file was opened successfully. */
public boolean openAndAddToRecent(String path) {
open(path);
if (!error)
Menus.addOpenRecentItem(path);
return !error;
}
/**
* Attempts to open the specified file as a tiff, bmp, dicom, fits,
* pgm, gif or jpeg image. Returns an ImagePlus object if successful.
* Modified by Gregory Jefferis to call HandleExtraFileTypes plugin if
* the file type is unrecognised.
* @see ij.IJ#openImage(String)
*/
public ImagePlus openImage(String directory, String name) {
ImagePlus imp;
FileOpener.setSilentMode(silentMode);
if (directory.length()>0 && !(directory.endsWith("/")||directory.endsWith("\\")))
directory += Prefs.separator;
OpenDialog.setLastDirectory(directory);
OpenDialog.setLastName(name);
String path = directory+name;
this.fileType = getFileType(path);
if (IJ.debugMode) IJ.log("openImage: \""+types[this.fileType]+"\", "+path);
switch (this.fileType) {
case TIFF:
imp = openTiff(directory, name);
return imp;
case DICOM: case TIFF_AND_DICOM:
imp = (ImagePlus)IJ.runPlugIn("ij.plugin.DICOM", path);
if (imp.getWidth()!=0) return imp; else return null;
case FITS:
imp = (ImagePlus)IJ.runPlugIn("ij.plugin.FITS_Reader", path);
if (imp.getWidth()!=0) return imp; else return null;
case PGM:
imp = (ImagePlus)IJ.runPlugIn("ij.plugin.PGM_Reader", path);
if (imp.getWidth()!=0) {
if (imp.getStackSize()==3 && imp.getBitDepth()==16)
imp = new CompositeImage(imp, IJ.COMPOSITE);
return imp;
} else
return null;
case JPEG:
imp = openJpegOrGif(directory, name);
if (imp!=null&&imp.getWidth()!=0) return imp; else return null;
case GIF:
imp = (ImagePlus)IJ.runPlugIn("ij.plugin.GIF_Reader", path);
if (imp!=null&&imp.getWidth()!=0) return imp; else return null;
case PNG:
imp = openUsingImageIO(directory+name);
if (imp!=null&&imp.getWidth()!=0) return imp; else return null;
case BMP:
imp = (ImagePlus)IJ.runPlugIn("ij.plugin.BMP_Reader", path);
if (imp.getWidth()!=0) return imp; else return null;
case ZIP:
return openZip(path);
case AVI:
AVI_Reader reader = new AVI_Reader();
reader.setVirtual(true);
reader.displayDialog(!IJ.macroRunning());
reader.run(path);
return reader.getImagePlus();
case JAVA_OR_TEXT:
if (name.endsWith(".txt"))
return openTextImage(directory,name);
else
return null;
case UNKNOWN: case TEXT:
imp = null;
if (name.endsWith(".lsm"))
useHandleExtraFileTypes = true; // use LSM_Reader to opem .lsm files
if (!useHandleExtraFileTypes)
imp = openUsingBioFormats(path);
useHandleExtraFileTypes = false;
if (imp!=null)
return imp;
else
return openUsingHandleExtraFileTypes(path);
default:
return null;
}
}
public ImagePlus openTempImage(String directory, String name) {
ImagePlus imp = openImage(directory, name);
if (imp!=null)
imp.setTemporary();
return imp;
}
// Call HandleExtraFileTypes plugin to see if it can handle unknown formats
// or files in TIFF format that the built in reader is unable to open.
private ImagePlus openUsingHandleExtraFileTypes(String path) {
File f = new File(path);
if (!f.exists())
return null;
int nImages = WindowManager.getImageCount();
int[] wrap = new int[] {this.fileType};
ImagePlus imp = openWithHandleExtraFileTypes(path, wrap);
if (imp!=null && imp.getNChannels()>1)
imp = new CompositeImage(imp, IJ.COLOR);
this.fileType = wrap[0];
if (imp==null && (this.fileType==UNKNOWN||this.fileType==TIFF) && WindowManager.getImageCount()==nImages)
IJ.error("Opener", "Unsupported format or file not found:\n"+path);
return imp;
}
String getPath() {
OpenDialog od = new OpenDialog("Open", "");
String dir = od.getDirectory();
String name = od.getFileName();
if (name==null)
return null;
else
return dir+name;
}
/** Opens the specified text file as a float image. */
public ImagePlus openTextImage(String dir, String name) {
String path = dir+name;
TextReader tr = new TextReader();
ImageProcessor ip = tr.open(path);
return ip!=null?new ImagePlus(name,ip):null;
}
/**
* Attempts to open the specified url as a tiff, zip compressed tiff,
* dicom, gif or jpeg. Tiff file names must end in ".tif", ZIP file names
* must end in ".zip" and dicom file names must end in ".dcm". Returns an
* ImagePlus object if successful.
* @see ij.IJ#openImage(String)
*/
public ImagePlus openURL(String url) {
url = updateUrl(url);
if (IJ.debugMode) IJ.log("OpenURL: "+url);
ImagePlus imp = openCachedImage(url);
if (imp!=null)
return imp;
try {
String name = "";
int index = url.lastIndexOf('/');
if (index==-1)
index = url.lastIndexOf('\\');
if (index>0)
name = url.substring(index+1);
else
throw new MalformedURLException("Invalid URL: "+url);
if (url.indexOf(" ")!=-1)
url = url.replaceAll(" ", "%20");
URL u = new URL(url);
IJ.showStatus(""+url);
String lurl = url.toLowerCase(Locale.US);
if (lurl.endsWith(".tif")) {
this.url = url;
imp = openTiff(u.openStream(), name);
} else if (lurl.endsWith(".zip"))
imp = openZipUsingUrl(u);
else if (lurl.endsWith(".jpg") || lurl.endsWith(".jpeg") || lurl.endsWith(".gif"))
imp = openJpegOrGifUsingURL(name, u);
else if (lurl.endsWith(".dcm") || lurl.endsWith(".ima")) {
imp = (ImagePlus)IJ.runPlugIn("ij.plugin.DICOM", url);
if (imp!=null && imp.getWidth()==0) imp = null;
} else if (lurl.endsWith(".png"))
imp = openPngUsingURL(name, u);
else {
URLConnection uc = u.openConnection();
String type = uc.getContentType();
if (type!=null && (type.equals("image/jpeg")||type.equals("image/gif")))
imp = openJpegOrGifUsingURL(name, u);
else if (type!=null && type.equals("image/png"))
imp = openPngUsingURL(name, u);
else
imp = openWithHandleExtraFileTypes(url, new int[]{0});
}
IJ.showStatus("");
return imp;
} catch (Exception e) {
String msg = e.getMessage();
if (msg==null || msg.equals(""))
msg = "" + e;
msg += "\n"+url;
IJ.error("Open URL", msg);
return null;
}
}
/** Can't open imagej.nih.gov URLs due to encryption so redirect to imagej.net mirror. */
public static String updateUrl(String url) {
if (url==null || !url.contains("nih.gov"))
return url;
if (IJ.isJava18())
url = url.replace("http:", "https:");
else {
url = url.replace("imagej.nih.gov/ij", "imagej.net");
url = url.replace("rsb.info.nih.gov/ij", "imagej.net");
url = url.replace("rsbweb.nih.gov/ij", "imagej.net");
}
return url;
}
private ImagePlus openCachedImage(String url) {
if (url==null)
return null;
String ijDir = IJ.getDirectory("imagej");
if (ijDir==null)
return null;
int slash = url.lastIndexOf('/');
File file = new File(ijDir + "samples", url.substring(slash+1));
if (!file.exists())
return null;
if (url.endsWith(".gif")) // ij.plugin.GIF_Reader does not correctly handle inverting LUTs
return openJpegOrGif(file.getParent()+File.separator, file.getName());
return IJ.openImage(file.getPath());
}
/** Used by open() and IJ.open() to open text URLs. */
void openTextURL(String url) {
if (url.endsWith(".pdf")||url.endsWith(".zip"))
return;
String text = IJ.openUrlAsString(url);
if (text!=null && text.startsWith("<Error: ")) {
IJ.error("Open Text URL", text);
return;
}
String name = url.substring(7);
int index = name.lastIndexOf("/");
int len = name.length();
if (index==len-1)
name = name.substring(0, len-1);
else if (index!=-1 && index<len-1)
name = name.substring(index+1);
name = name.replaceAll("%20", " ");
Editor ed = new Editor(name);
ed.setSize(600, 300);
ed.create(name, text);
IJ.showStatus("");
}
public ImagePlus openWithHandleExtraFileTypes(String path, int[] fileTypes) {
ImagePlus imp = null;
if (path.endsWith(".db")) {
// skip hidden Thumbs.db files on Windows
fileTypes[0] = CUSTOM;
return null;
}
try {
imp = (ImagePlus)IJ.runPlugIn("HandleExtraFileTypes", path);
} catch(Exception e) {
if (IJ.debugMode) IJ.log("openWithHandleExtraFileTypes:\n"+path+"\n"+e);
imp = null;
}
if (imp==null)
return null;
FileInfo fi = imp.getOriginalFileInfo();
if (fi==null) {
fi = new FileInfo();
fi.width = imp.getWidth();
fi.height = imp.getHeight();
fi.directory = getDir(path);
fi.fileName = getName(path);
imp.setFileInfo(fi);
}
if (imp.getWidth()>0 && imp.getHeight()>0) {
fileTypes[0] = CUSTOM;
return imp;
} else {
if (imp.getWidth()==-1)
fileTypes[0] = CUSTOM; // plugin opened image so don't display error
return null;
}
}
/** Opens the ZIP compressed TIFF or DICOM at the specified URL. */
ImagePlus openZipUsingUrl(URL url) throws IOException {
URLConnection uc = url.openConnection();
InputStream in = uc.getInputStream();
ZipInputStream zis = new ZipInputStream(in);
ZipEntry entry = zis.getNextEntry();
if (entry==null) {
zis.close();
return null;
}
String name = entry.getName();
if (!(name.endsWith(".tif")||name.endsWith(".dcm")))
throw new IOException("This ZIP archive does not appear to contain a .tif or .dcm file\n"+name);
if (name.endsWith(".dcm"))
return openDicomStack(zis, entry);
else
return openTiff(zis, name);
}
ImagePlus openDicomStack(ZipInputStream zis, ZipEntry entry) throws IOException {
ImagePlus imp = null;
int count = 0;
ImageStack stack = null;
while (true) {
if (count>0) entry = zis.getNextEntry();
if (entry==null) break;
String name = entry.getName();
ImagePlus imp2 = null;
if (name.endsWith(".dcm")) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[4096];
int len, byteCount=0, progress=0;
while (true) {
len = zis.read(buf);
if (len<0) break;
out.write(buf, 0, len);
byteCount += len;
//IJ.showProgress((double)(byteCount%fileSize)/fileSize);
}
byte[] bytes = out.toByteArray();
out.close();
InputStream is = new ByteArrayInputStream(bytes);
DICOM dcm = new DICOM(is);
dcm.run(name);
imp2 = dcm;
is.close();
}
zis.closeEntry();
if (imp2==null) continue;
count++;
String label = imp2.getTitle();
String info = (String)imp2.getProperty("Info");
if (info!=null) label += "\n" + info;
if (count==1) {
imp = imp2;
imp.getStack().setSliceLabel(label, 1);
} else {
stack = imp.getStack();
stack.addSlice(label, imp2.getProcessor());
imp.setStack(stack);
}
}
zis.close();
IJ.showProgress(1.0);
if (count==0)
throw new IOException("This ZIP archive does not appear to contain any .dcm files");
return imp;
}
ImagePlus openJpegOrGifUsingURL(String title, URL url) {
if (url==null) return null;
Image img = Toolkit.getDefaultToolkit().createImage(url);
if (img!=null) {
ImagePlus imp = new ImagePlus(title, img);
return imp;
} else
return null;
}
ImagePlus openPngUsingURL(String title, URL url) {
if (url==null)
return null;
Image img = null;
try {
InputStream in = url.openStream();
img = ImageIO.read(in);
} catch (FileNotFoundException e) {
IJ.error("Open PNG Using URL", ""+e);
} catch (IOException e) {
IJ.handleException(e);
}
if (img!=null) {
ImagePlus imp = new ImagePlus(title, img);
return imp;
} else
return null;
}
ImagePlus openJpegOrGif(String dir, String name) {
ImagePlus imp = null;
Image img = Toolkit.getDefaultToolkit().createImage(dir+name);
if (img!=null) {
try {
imp = new ImagePlus(name, img);
} catch (Exception e) {
IJ.error("Opener", e.getMessage()+"\n(Note: ImageJ cannot open CMYK JPEGs)\n \n"+dir+name);
return null; // error loading image
}
if (imp.getType()==ImagePlus.COLOR_RGB)
convertGrayJpegTo8Bits(imp);
FileInfo fi = new FileInfo();
fi.fileFormat = fi.GIF_OR_JPG;
fi.fileName = name;
fi.directory = dir;
imp.setFileInfo(fi);
}
if (imp != null) { // correct iPhone photo orientation (Norbert Vischer)
String exifText = new ImageInfo().getExifData(imp);
if (exifText != null) {
String[] lines = exifText.split("\n");
for (int jj = 0; jj < lines.length; jj++) {
int orientationIndex = lines[jj].indexOf("Orientation:");
int rotateIndex = lines[jj].indexOf("Rotate");
if (orientationIndex >= 0 && rotateIndex >= 0) {
String rest = lines[jj].substring(rotateIndex);
rest = rest.replace(")", " ");
String[] parts = rest.split(" ");
if (parts.length >= 2) {
ImageProcessor ip = imp.getProcessor();
double angle = Double.parseDouble(parts[1]);
ImageProcessor ip2 = null;
if (angle == 90)
ip2 = ip.rotateRight();
else if (angle == 180) {
ip2 = ip.rotateRight();
ip2 = ip2.rotateRight();
} else if (angle == 270)
ip2 = ip.rotateLeft();
if (ip2!=null)
imp.setProcessor(ip2);
break;
}
}
}
}
}
return imp;
}
public static ImagePlus openUsingImageIO(String path) {
ImagePlus imp = null;
BufferedImage img = null;
File f = new File(path);
try {
img = ImageIO.read(f);
} catch (Exception e) {
IJ.error("Open Using ImageIO", ""+e);
}
if (img==null)
return null;
if (IJ.debugMode) IJ.log("type="+img.getType()+", alpha="+img.getColorModel().hasAlpha()+", bands="+img.getSampleModel().getNumBands());
boolean custom8Bit = img.getType()==0 && img.getSampleModel().getDataType()==0;
if (img.getColorModel().hasAlpha() || custom8Bit) {
int width = img.getWidth();
int height = img.getHeight();
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics g = bi.getGraphics();
g.setColor(Color.white);
g.fillRect(0,0,width,height);
g.drawImage(img, 0, 0, null);
img = bi;
}
imp = new ImagePlus(f.getName(), img);
if (imp.getBitDepth()==16 && imp.getStackSize()>1)
imp = new CompositeImage(imp, IJ.COMPOSITE);
FileInfo fi = new FileInfo();
fi.fileFormat = fi.IMAGEIO;
fi.fileName = f.getName();
String parent = f.getParent();
if (parent!=null)
fi.directory = parent + File.separator;
imp.setFileInfo(fi);
return imp;
}
/** Converts the specified RGB image to 8-bits if the 3 channels are identical. */
public static void convertGrayJpegTo8Bits(ImagePlus imp) {
ImageProcessor ip = imp.getProcessor();
if (ip.getBitDepth()==24 && ip.isGrayscale()) {
IJ.showStatus("Converting to 8-bit grayscale");
new ImageConverter(imp).convertToGray8();
}
}
/** Are all the images in this file the same size and type? */
boolean allSameSizeAndType(FileInfo[] info) {
boolean sameSizeAndType = true;
boolean contiguous = true;
long startingOffset = info[0].getOffset();
int size = info[0].width*info[0].height*info[0].getBytesPerPixel();
for (int i=1; i<info.length; i++) {
sameSizeAndType &= info[i].fileType==info[0].fileType
&& info[i].width==info[0].width
&& info[i].height==info[0].height;
contiguous &= info[i].getOffset()==startingOffset+i*size;
}
if (contiguous && info[0].fileType!=FileInfo.RGB48)
info[0].nImages = info.length;
//if (IJ.debugMode) {
// IJ.log("sameSizeAndType: " + sameSizeAndType);
// IJ.log("contiguous: " + contiguous);
//}
return sameSizeAndType;
}
/** Attemps to open a tiff file as a stack. Returns
an ImagePlus object if successful. */
public ImagePlus openTiffStack(FileInfo[] info) {
if (info.length>1 && !allSameSizeAndType(info))
return null;
FileInfo fi = info[0];
if (fi.nImages>1)
return new FileOpener(fi).openImage(); // open contiguous images as stack
else {
ColorModel cm = createColorModel(fi);
ImageStack stack = new ImageStack(fi.width, fi.height, cm);
Object pixels = null;
long skip = fi.getOffset();
int imageSize = fi.width*fi.height*fi.getBytesPerPixel();
if (info[0].fileType==FileInfo.GRAY12_UNSIGNED) {
imageSize = (int)(fi.width*fi.height*1.5);
if ((imageSize&1)==1) imageSize++; // add 1 if odd
} else if (info[0].fileType==FileInfo.GRAY10_UNSIGNED) {
imageSize = (int)(fi.width*fi.height*1.25);
if ((imageSize&1)==1) imageSize++; // add 1 if odd
} else if (info[0].fileType==FileInfo.BITMAP) {
int scan=(int)Math.ceil(fi.width/8.0);
imageSize = scan*fi.height;
}
long loc = 0L;
int nChannels = 1;
try {
InputStream is = createInputStream(fi);
ImageReader reader = new ImageReader(fi);
IJ.resetEscape();
for (int i=0; i<info.length; i++) {
nChannels = 1;
Object[] channels = null;
if (!silentMode)
IJ.showStatus("Reading: " + (i+1) + "/" + info.length);
if (IJ.escapePressed()) {
IJ.beep();
IJ.showProgress(1.0);
return null;
}
fi.stripOffsets = info[i].stripOffsets;
fi.stripLengths = info[i].stripLengths;
int bpp = info[i].getBytesPerPixel();
if (info[i].samplesPerPixel>1 && !(bpp==3||bpp==4||bpp==6)) {
nChannels = fi.samplesPerPixel;
channels = new Object[nChannels];
for (int c=0; c<nChannels; c++) {
pixels = reader.readPixels(is, c==0?skip:0L);
channels[c] = pixels;
}
} else
pixels = reader.readPixels(is, skip);
if (pixels==null && channels==null) break;
loc += imageSize*nChannels+skip;
if (i<(info.length-1)) {
skip = info[i+1].getOffset()-loc;
if (info[i+1].compression>=FileInfo.LZW) skip = 0;
if (skip<0L) {
IJ.error("Opener", "Unexpected image offset");
break;
}
}
if (fi.fileType==FileInfo.RGB48) {
Object[] pixels2 = (Object[])pixels;
stack.addSlice(null, pixels2[0]);
stack.addSlice(null, pixels2[1]);
stack.addSlice(null, pixels2[2]);
isRGB48 = true;
} else if (nChannels>1) {
for (int c=0; c<nChannels; c++) {
if (channels[c]!=null)
stack.addSlice(null, channels[c]);
}
} else
stack.addSlice(null, pixels);
IJ.showProgress(i, info.length);
}
is.close();
}
catch (Exception e) {
IJ.handleException(e);
}
catch(OutOfMemoryError e) {
IJ.outOfMemory(fi.fileName);
stack.deleteLastSlice();
stack.deleteLastSlice();
}
IJ.showProgress(1.0);
if (stack.size()==0)
return null;
if (fi.fileType==FileInfo.GRAY16_UNSIGNED||fi.fileType==FileInfo.GRAY12_UNSIGNED
||fi.fileType==FileInfo.GRAY32_FLOAT||fi.fileType==FileInfo.RGB48
||fi.fileType==FileInfo.GRAY10_UNSIGNED) {
ImageProcessor ip = stack.getProcessor(1);
ip.resetMinAndMax();
stack.update(ip);
}
//if (fi.whiteIsZero)
// new StackProcessor(stack, stack.getProcessor(1)).invert();
ImagePlus imp = new ImagePlus(fi.fileName, stack);
new FileOpener(fi).setCalibration(imp);
imp.setFileInfo(fi);
if (fi.info!=null)
imp.setProperty("Info", fi.info);
if (fi.description!=null && fi.description.contains("order=zct"))
new HyperStackConverter().shuffle(imp, HyperStackConverter.ZCT);
int stackSize = stack.size();
if (nChannels>1 && (stackSize%nChannels)==0) {
imp.setDimensions(nChannels, stackSize/nChannels, 1);
imp = new CompositeImage(imp, IJ.COMPOSITE);
imp.setOpenAsHyperStack(true);
} else if (imp.getNChannels()>1)
imp = makeComposite(imp, fi);
IJ.showProgress(1.0);
return imp;
}
}
/** Attempts to open the specified file as a tiff.
Returns an ImagePlus object if successful. */
public ImagePlus openTiff(String directory, String name) {
TiffDecoder td = new TiffDecoder(directory, name);
if (IJ.debugMode) td.enableDebugging();
FileInfo[] info=null;
try {
info = td.getTiffInfo();
} catch (IOException e) {
// try opening using bio-formats
this.fileType = TIFF;
directory = IJ.addSeparator(directory);
return openUsingHandleExtraFileTypes(directory+name);
}
if (info==null)
return null;
return openTiff2(info);
}
/** Opens the nth image of the specified TIFF stack. */
public ImagePlus openTiff(String path, int n) {
TiffDecoder td = new TiffDecoder(getDir(path), getName(path));
if (IJ.debugMode) td.enableDebugging();
FileInfo[] info=null;
try {
info = td.getTiffInfo();
} catch (IOException e) {
String msg = e.getMessage();
if (msg==null||msg.equals("")) msg = ""+e;
IJ.error("Open TIFF", msg);
return null;
}
if (info==null) return null;
FileInfo fi = info[0];
if (info.length==1 && fi.nImages>1) {
if (n<1 || n>fi.nImages)
throw new IllegalArgumentException("N out of 1-"+fi.nImages+" range");
long size = fi.width*fi.height*fi.getBytesPerPixel();
fi.longOffset = fi.getOffset() + (n-1)*(size+fi.getGap());
fi.offset = 0;
fi.nImages = 1;
} else {
if (n<1 || n>info.length)
throw new IllegalArgumentException("N out of 1-"+info.length+" range");
fi.longOffset = info[n-1].getOffset();
fi.offset = 0;
fi.stripOffsets = info[n-1].stripOffsets;
fi.stripLengths = info[n-1].stripLengths;
}
FileOpener fo = new FileOpener(fi);
return fo.openImage();
}
/** Returns the FileInfo of the specified TIFF file. */
public static FileInfo[] getTiffFileInfo(String path) {
Opener o = new Opener();
TiffDecoder td = new TiffDecoder(o.getDir(path), o.getName(path));
if (IJ.debugMode) td.enableDebugging();
try {
return td.getTiffInfo();
} catch (IOException e) {
return null;
}
}
/** Attempts to open the specified inputStream as a
TIFF, returning an ImagePlus object if successful. */
public ImagePlus openTiff(InputStream in, String name) {
FileInfo[] info = null;
try {
TiffDecoder td = new TiffDecoder(in, name);
if (IJ.debugMode) td.enableDebugging();
info = td.getTiffInfo();
} catch (FileNotFoundException e) {
IJ.error("Open TIFF", "File not found: "+e.getMessage());
return null;
} catch (Exception e) {
IJ.error("Open TIFF", ""+e);
return null;
}
if (url!=null && info!=null && info.length==1 && info[0].inputStream!=null) {
try {
info[0].inputStream.close();
} catch (IOException e) {}
try {
info[0].inputStream = new URL(url).openStream();
} catch (Exception e) {
IJ.error("Open TIFF", ""+e);
return null;
}
}
return openTiff2(info);
}
/** Opens a single TIFF or DICOM contained in a ZIP archive,
or a ZIPed collection of ".roi" files created by the ROI manager. */
public ImagePlus openZip(String path) {
ImagePlus imp = null;
try {
ZipInputStream zis = new ZipInputStream(new FileInputStream(path));
ZipEntry entry = zis.getNextEntry();
if (entry==null) {
zis.close();
return null;
}
String name = entry.getName();
if (name.endsWith(".roi")) {
zis.close();
if (!silentMode)
if (IJ.isMacro() && Interpreter.isBatchMode() && RoiManager.getInstance()==null)
IJ.log("Use roiManager(\"Open\", path) instead of open(path)\nto open ROI sets in batch mode macros.");
else
IJ.runMacro("roiManager(\"Open\", getArgument());", path);
return null;
}
if (name.endsWith(".tif")) {
imp = openTiff(zis, name);
} else if (name.endsWith(".dcm")) {
DICOM dcm = new DICOM(zis);
dcm.run(name);
imp = dcm;
} else {
zis.close();
String msg = "This ZIP archive does not contain a TIFF or DICOM file, or ROIs:\n "+path;
if (silentMode)
IJ.log(msg);
else
IJ.error("Opener", msg);
return null;
}
zis.close();
} catch (Exception e) {
IJ.error("Opener", ""+e);
return null;
}
File f = new File(path);
FileInfo fi = imp.getOriginalFileInfo();
if (fi!=null) {
fi.fileFormat = FileInfo.ZIP_ARCHIVE;
fi.fileName = f.getName();
String parent = f.getParent();
if (parent!=null)
fi.directory = parent+File.separator;
}
return imp;
}
/** Deserialize a byte array that was serialized using the FileSaver.serialize(). */
public ImagePlus deserialize(byte[] bytes) {
ByteArrayInputStream stream = new ByteArrayInputStream(bytes);
TiffDecoder decoder = new TiffDecoder(stream, "Untitled");
if (IJ.debugMode)
decoder.enableDebugging();
FileInfo[] info = null;
try {
info = decoder.getTiffInfo();
} catch (IOException e) {
return null;
}
FileOpener opener = new FileOpener(info[0]);
ImagePlus imp = opener.openImage();
if (imp==null)
return null;
imp.setTitle(info[0].fileName);
imp = makeComposite(imp, info[0]);
return imp;
}
private ImagePlus makeComposite(ImagePlus imp, FileInfo fi) {
int c = imp.getNChannels();
boolean composite = c>1 && fi.description!=null && fi.description.indexOf("mode=")!=-1;
if (c>1 && (imp.getOpenAsHyperStack()||composite) && !imp.isComposite() && imp.getType()!=ImagePlus.COLOR_RGB) {
int mode = IJ.COLOR;
if (fi.description!=null) {
if (fi.description.indexOf("mode=composite")!=-1)
mode = IJ.COMPOSITE;
else if (fi.description.indexOf("mode=gray")!=-1)
mode = IJ.GRAYSCALE;
}
imp = new CompositeImage(imp, mode);
}
return imp;
}
public String getName(String path) {
int i = path.lastIndexOf('/');
if (i==-1)
i = path.lastIndexOf('\\');
if (i>0)
return path.substring(i+1);
else
return path;
}
public String getDir(String path) {
int i = path.lastIndexOf('/');
if (i==-1)
i = path.lastIndexOf('\\');
if (i>0)
return path.substring(0, i+1);
else
return "";
}
ImagePlus openTiff2(FileInfo[] info) {
if (info==null)
return null;
ImagePlus imp = null;
if (IJ.debugMode) // dump tiff tags
IJ.log(info[0].debugInfo);
if (info.length>1) { // try to open as stack
imp = openTiffStack(info);
if (imp!=null)
return imp;
}
FileOpener fo = new FileOpener(info[0]);
imp = fo.openImage();
if (imp==null)
return null;
int[] offsets = info[0].stripOffsets;
if (offsets!=null&&offsets.length>1) {
long firstOffset = (long)offsets[0]&0xffffffffL;
long lastOffset = (long)offsets[offsets.length-1]&0xffffffffL;
if (lastOffset<firstOffset)
ij.IJ.run(imp, "Flip Vertically", "stack");
}
imp = makeComposite(imp, info[0]);
if (imp.getBitDepth()==32 && imp.getTitle().startsWith("FFT of"))
return openFFT(imp);
else
return imp;
}
private ImagePlus openFFT(ImagePlus imp) {
ImageProcessor ip = imp.getProcessor();
FHT fht = new FHT(ip, true);
ImageProcessor ps = fht.getPowerSpectrum();
ImagePlus imp2 = new ImagePlus(imp.getTitle(), ps);
imp2.setProperty("FHT", fht);
imp2.setProperty("Info", imp.getInfoProperty());
fht.originalWidth = (int)imp2.getNumericProperty("width");
fht.originalHeight = (int)imp2.getNumericProperty("height");
fht.originalBitDepth = (int)imp2.getNumericProperty("bitdepth");
fht.originalColorModel = ip.getColorModel();
imp2.setCalibration(imp.getCalibration());
return imp2;
}
/** Attempts to open the specified ROI, returning null if unsuccessful. */
public Roi openRoi(String path) {
Roi roi = null;
RoiDecoder rd = new RoiDecoder(path);
try {roi = rd.getRoi();}
catch (IOException e) {
IJ.error("RoiDecoder", e.getMessage());
return null;
}
return roi;
}
/** Opens an image file using the Bio-Formats plugin. */
public static ImagePlus openUsingBioFormats(String path) {
String className = "loci.plugins.BF";
String methodName = "openImagePlus";
try {
Class c = IJ.getClassLoader().loadClass(className);
if (c==null)
return null;
Class[] argClasses = new Class[1];
argClasses[0] = methodName.getClass();
Method m = c.getMethod(methodName, argClasses);
Object[] args = new Object[1];
args[0] = path;
Object obj = m.invoke(null, args);
ImagePlus[] images = obj!=null?(ImagePlus[])obj:null;
if (images==null || images.length==0)
return null;
ImagePlus imp = images[0];
return imp;
} catch(Exception e) {}
return null;
}
/*
public static boolean isRGBStack(ImagePlus imp) {
if (imp==null)
return false;
boolean rgb = imp.getStackSize()==3 && imp.getNChannels()==3 && imp.getBitDepth()==8;
if (!rgb)
return false;
for (int i=1; i<=3; i++) {
imp.setSlice(i);
LUT lut = imp.getProcessor().getLut();
if (lut==null) {
rgb = false;
break;
}
byte[] bytes = lut.getBytes();
if (bytes==null) {
rgb = false;
break;
}
if (!((i==0 && (bytes[255]&255)==255 && (bytes[511]&255)==0 && (bytes[767]&255)==0)
|| (i==1 && (bytes[255]&255)==0 && (bytes[511]&255)==255 && (bytes[767]&255)==0)
|| (i==2 && (bytes[255]&255)==0 && (bytes[511]&255)==0 && (bytes[767]&255)==255))) {
rgb = false;
break;
}
}
imp.setSlice(1);
return rgb;
}
*/
/** Opens a lookup table (LUT) and returns it as a LUT object, or returns null if there is an error.
* @see ij.ImagePlus#setLut
*/
public static LUT openLut(String filePathOrUrl) {
return LutLoader.openLut(filePathOrUrl);
}
/** Opens a tab or comma delimited text file in the Results window. */
public static void openResultsTable(String path) {
try {
ResultsTable rt = ResultsTable.open(path);
if (rt!=null) {
rt.showRowNumbers(true);
rt.show("Results");
}
} catch(IOException e) {
IJ.error("Open Results", e.getMessage());
}
}
/** Opens a tab or comma delimited text file. */
public static void openTable(String path) {
String name = "";
if (path==null || path.equals("")) {
OpenDialog od = new OpenDialog("Open Table...");
String dir = od.getDirectory();
name = od.getFileName();
if (name==null)
return;
else
path = dir+name;
} else {
name = (new Opener()).getName(path);
if (name.startsWith("Results."))
name = "Results";
}
try {
ResultsTable rt = ResultsTable.open(path);
if (rt!=null)
rt.show(name);
} catch(IOException e) {
IJ.error("Open Table", e.getMessage());
}
}
public static String getFileFormat(String path) {
if (!((new File(path)).exists()))
return("not found");
else
return Opener.types[(new Opener()).getFileType(path)];
}
/**
Attempts to determine the image file type by looking for
'magic numbers' and the file name extension.
*/
public int getFileType(String path) {
if (openUsingPlugins && !path.endsWith(".txt") && !path.endsWith(".java"))
return UNKNOWN;
File file = new File(path);
String name = file.getName();
InputStream is;
byte[] buf = new byte[132];
try {
is = new FileInputStream(file);
is.read(buf, 0, 132);
is.close();
} catch (IOException e) {
return UNKNOWN;
}
int b0=buf[0]&255, b1=buf[1]&255, b2=buf[2]&255, b3=buf[3]&255;
//IJ.log("getFileType: "+ name+" "+b0+" "+b1+" "+b2+" "+b3);
// ImspectorPro MSR
if (name.endsWith(".msr")||name.endsWith(".MSR"))
return UNKNOWN; // Open with Bio-formats plugin
// Combined TIFF and DICOM created by GE Senographe scanners
if (buf[128]==68 && buf[129]==73 && buf[130]==67 && buf[131]==77
&& ((b0==73 && b1==73)||(b0==77 && b1==77)))
return TIFF_AND_DICOM;
// Big-endian TIFF ("MM")
if (name.endsWith(".lsm"))
return UNKNOWN; // The LSM Reader plugin opens these files
// OME TIFF
if (bioformats && name.contains(".ome.tif"))
return UNKNOWN; // Open with Bio-formats plugin
// TIFF
if (b0==73 && b1==73 && b2==42 && b3==0 && !(bioformats&&name.endsWith(".flex")))
return TIFF;
// Little-endian TIFF ("II")
if (b0==77 && b1==77 && b2==0 && b3==42)
return TIFF;
// JPEG
if (b0==255 && b1==216 && b2==255)
return JPEG;
// GIF ("GIF8")
if (b0==71 && b1==73 && b2==70 && b3==56)
return GIF;
name = name.toLowerCase(Locale.US);
// DICOM ("DICM" at offset 128)
if (buf[128]==68 && buf[129]==73 && buf[130]==67 && buf[131]==77 || name.endsWith(".dcm")) {
return DICOM;
}
// ACR/NEMA with first tag = 00002,00xx or 00008,00xx
if ((b0==8||b0==2) && b1==0 && b3==0 && !name.endsWith(".spe") && !name.equals("fid"))
return DICOM;
// PGM ("P1", "P4", "P2", "P5", "P3" or "P6")
if (b0==80&&(b1==49||b1==52||b1==50||b1==53||b1==51||b1==54)&&(b2==10||b2==13||b2==32||b2==9))
return PGM;
// Lookup table
if (name.endsWith(".lut"))
return LUT;
// PNG
if (b0==137 && b1==80 && b2==78 && b3==71)
return PNG;
// ZIP containing a TIFF
if (name.endsWith(".zip"))
return ZIP;
// FITS ("SIMP")
if ((b0==83 && b1==73 && b2==77 && b3==80) || name.endsWith(".fts.gz") || name.endsWith(".fits.gz"))
return FITS;
// Java source file, text file or macro
if (name.endsWith(".java") || name.endsWith(".txt") || name.endsWith(".ijm") || name.endsWith(".js")
|| name.endsWith(".bsh") || name.endsWith(".py") || name.endsWith(".html"))
return JAVA_OR_TEXT;
// ImageJ, NIH Image, Scion Image for Windows ROI
if (b0==73 && b1==111) // "Iout"
return ROI;
// ObjectJ project
if ((b0=='o' && b1=='j' && b2=='j' && b3==0) || name.endsWith(".ojj") )
return OJJ;
// Results table (tab-delimited or comma-separated tabular text)
if (name.endsWith(".xls") || name.endsWith(".csv") || name.endsWith(".tsv"))
return TABLE;
// AVI
if (name.endsWith(".avi"))
return AVI;
// Text file
boolean isText = true;
for (int i=0; i<10; i++) {
int c = buf[i]&255;
if ((c<32&&c!=9&&c!=10&&c!=13) || c>126) {
isText = false;
break;
}
}
if (isText)
return TEXT;
// BMP ("BM")
if ((b0==66 && b1==77)||name.endsWith(".dib"))
return BMP;
// RAW
if (name.endsWith(".raw") && !Prefs.skipRawDialog)
return RAW;
return UNKNOWN;
}
/** Returns an IndexColorModel for the image specified by this FileInfo. */
ColorModel createColorModel(FileInfo fi) {
if (fi.lutSize>0)
return new IndexColorModel(8, fi.lutSize, fi.reds, fi.greens, fi.blues);
else
return LookUpTable.createGrayscaleColorModel(fi.whiteIsZero);
}
/** Returns an InputStream for the image described by this FileInfo. */
InputStream createInputStream(FileInfo fi) throws IOException, MalformedURLException {
if (fi.inputStream!=null)
return fi.inputStream;
else if (fi.url!=null && !fi.url.equals(""))
return new URL(fi.url+fi.fileName).openStream();
else {
File f = new File(fi.getFilePath());
if (f==null || f.isDirectory())
return null;
else {
InputStream is = new FileInputStream(f);
if (fi.compression>=FileInfo.LZW || (fi.stripOffsets!=null&&fi.stripOffsets.length>1))
is = new RandomAccessStream(is);
return is;
}
}
}
void openRGB48(ImagePlus imp) {
isRGB48 = false;
int stackSize = imp.getStackSize();
imp.setDimensions(3, stackSize/3, 1);
imp = new CompositeImage(imp, IJ.COMPOSITE);
imp.show();
}
/** The "Opening: path" status message is not displayed in silent mode. */
public void setSilentMode(boolean mode) {
silentMode = mode;
}
/** Open all images using HandleExtraFileTypes. Set from
a macro using setOption("openUsingPlugins", true). */
public static void setOpenUsingPlugins(boolean b) {
openUsingPlugins = b;
}
/** Returns the state of the openUsingPlugins flag. */
public static boolean getOpenUsingPlugins() {
return openUsingPlugins;
}
}
|