ij.io.FileSaver Java Examples

The following examples show how to use ij.io.FileSaver. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: FSLoader.java    From TrakEM2 with GNU General Public License v3.0 6 votes vote down vote up
/** Returns the path where the imp is saved to: the storage folder plus a name. */
public String handlePathlessImage(final ImagePlus imp) {
	FileInfo fi = imp.getOriginalFileInfo();
	if (null == fi) fi = imp.getFileInfo();
	if (null == fi.fileName || fi.fileName.equals("")) {
		fi.fileName = "img_" + System.currentTimeMillis() + ".tif";
	}
	if (!fi.fileName.endsWith(".tif")) fi.fileName += ".tif";
	fi.directory = dir_storage;
	if (imp.getNSlices() > 1) {
		new FileSaver(imp).saveAsTiffStack(dir_storage + fi.fileName);
	} else {
		new FileSaver(imp).saveAsTiff(dir_storage + fi.fileName);
	}
	Utils.log2("Saved a copy into the storage folder:\n" + dir_storage + fi.fileName);
	return dir_storage + fi.fileName;
}
 
Example #2
Source File: IJImager.java    From DeconvolutionLab2 with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void save(RealSignal signal, String filename, Imager.Type type) {
	ImagePlus imp = build(signal, type);
	if (imp != null) {
		if (imp.getStackSize() == 1) {
			new FileSaver(imp).saveAsTiff(filename);
		}
		else {
			new FileSaver(imp).saveAsTiffStack(filename);
		}
	}
}
 
Example #3
Source File: Tree.java    From TrakEM2 with GNU General Public License v3.0 5 votes vote down vote up
/** The behavior is undefined if @param last is not a descendant of @param first. */
public void createReviewStack(final Node<T> first, final Node<T> last, final Tag tag, final String filepath, final int width, final int height, final double magnification, final int image_type) {
	try {
		final ImagePlus imp = project.getLoader().createLazyFlyThrough(generateRegions(first, last, width, height, magnification), magnification, image_type, this);
		imp.setTitle(imp.getTitle() + tag.toString());
		ij.IJ.redirectErrorMessages();
		new FileSaver(imp).saveAsZip(filepath);
	} catch (final Exception e) {
		IJError.print(e);
		Utils.log("\nERROR: NOT created review stack for " + tag.toString());
		return;
	}
}
 
Example #4
Source File: Loader.java    From TrakEM2 with GNU General Public License v3.0 5 votes vote down vote up
/** Returns the path to the saved image, or null if not saved. */
public String exportImage(final Patch patch, final ImagePlus imp, final String path, final boolean overwrite) {
	// if !overwrite, save only if not there already
	if (null == path || null == imp || (!overwrite && new File(path).exists())) return null;
	try {
		if (imp.getNSlices() > 1) new FileSaver(imp).saveAsTiffStack(path);
		else new FileSaver(imp).saveAsTiff(path);
	} catch (final Exception e) {
		Utils.log("Could not save an image for Patch #" + patch.getId() + " at: " + path);
		IJError.print(e);
		return null;
	}
	return path;
}
 
Example #5
Source File: Loader.java    From TrakEM2 with GNU General Public License v3.0 5 votes vote down vote up
/** Mipmaps for this image are generated asynchronously. */
public Patch addNewImage(final ImagePlus imp, final double x, final double y) {
	String filename = imp.getTitle();
	if (!filename.toLowerCase().endsWith(".tif")) filename += ".tif";
	final String path = getStorageFolder() + "/" + filename;
	new FileSaver(imp).saveAsTiff(path);
	final Patch pa = new Patch(Project.findProject(this), imp.getTitle(), x, y, imp);
	addedPatchFrom(path, pa);
	if (isMipMapsRegenerationEnabled()) regenerateMipMaps(pa);
	return pa;
}
 
Example #6
Source File: Stitch_Image_Grid_Sequence.java    From Stitching with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Stitch sequence of image grids (all grids must have the same X/Y configuration)
 * 
 * @param nSections
 * @param filenames
 * @param inputDirectory
 * @param gridLayout
 * @param handleRGB
 * @param fusionMethod
 * @param outputFileName
 * @param outputDirectory
 * @param overlap
 * @param startX
 * @param startY
 * @param startZ
 * @param startI
 * @param writeOnlyOutput
 * @param previewOnly
 * @param computeOverlap
 */
public static void stitchImageGridSequence(
		int nSections, 
		String filenames, 
		String inputDirectory, 
		GridLayout gridLayout, 
		String handleRGB, 
		String fusionMethod, 
		String outputFileName,
		String outputDirectory,
		double overlap, 
		int startX, 
		int startY,
		int startZ,
		int startI, 
		boolean writeOnlyOutput, 
		boolean previewOnly, 
		boolean computeOverlap) 
{
	// find how to parse
	String replaceZ = "{";
	int numZValues = 0;
	
	int z1 = filenames.indexOf("{z");
	int z2 = filenames.indexOf("z}");
	if (z1 >= 0 && z2 > 0)
	{
		numZValues = z2 - z1;
		for (int i = 0; i < numZValues; i++)
			replaceZ += "z";
		replaceZ += "}";
	}
	else
	{
		replaceZ = "\\\\\\\\";
	}
	
	final int gridSize = gridLayout.sizeX * gridLayout.sizeY;
	
	for(int z = 0; z < nSections; z++)
	{
		final int zs = z + startZ;
		final String file = filenames.replace(replaceZ, Stitch_Image_Grid.getLeadingZeros(numZValues, zs));
		final String outTileConfName = outputFileName.replace(replaceZ, Stitch_Image_Grid.getLeadingZeros(numZValues, zs)); 
		
		final ImagePlus fusedImage = 
			Stitch_Image_Grid.stitchImageGrid(file, inputDirectory, gridLayout, handleRGB, fusionMethod, 
				outTileConfName, overlap, startX, startY, startI, writeOnlyOutput, previewOnly, computeOverlap);
		
		if (fusedImage == null)
			return;
		
		final String outputFusedPath = outputDirectory + System.getProperty("file.separator") + fusedImage.getTitle() 
							+ "_" + Stitch_Image_Grid.getLeadingZeros(numZValues, zs) + ".tif"; 
		Log.info("Saving " + outputFusedPath +  " ... ");
		try 
		{
			new FileSaver(fusedImage).saveAsTiff(outputFusedPath);
		} 
		catch (Exception e) 
		{
			Log.error("Error while saving " + outputFusedPath, e);
			return;
		}
		Log.info("Saved");
		
		startI += gridSize;
		
		// Iteratively close fused images to avoid unnecessarily filling the screen 
		fusedImage.close();
	}
	
	Log.info("Image grid sequence stitching is done!");
	
}
 
Example #7
Source File: ConsensusWarpFieldBuilderInteractiveTest.java    From render with GNU General Public License v2.0 4 votes vote down vote up
private static void saveBoxes4And7() throws Exception {

        final int consensusRowCount = 10;
        final int consensusColumnCount = 10;

        final HierarchicalStack tier4Stack = HierarchicalStack.fromJson(TIER_STACK_004);
        final double tierScale = tier4Stack.getScale();
        final String groupId = "2214.0";
        final List<CanvasMatches> canvasMatchesList = CanvasMatches.fromJsonArray(MATCHES_OUTSIDE_2214);

        final CanvasNameToPointsMap nameToPointsForGroup = new CanvasNameToPointsMap(1 / tierScale);
        nameToPointsForGroup.addPointsForGroup(groupId, canvasMatchesList);

        final ResolvedTileSpecCollection alignedTiles = ResolvedTileSpecCollection.fromJson(ALIGNED_TILES);

        final AffineWarpField consensusField =
                buildConsensusField(tier4Stack, nameToPointsForGroup, alignedTiles,
                                    consensusRowCount, consensusColumnCount);

//        final AffineWarpFieldTransform foo = new AffineWarpFieldTransform(AffineWarpFieldTransform.EMPTY_OFFSETS, consensusField);
//        System.out.println(foo.getClass().getName());
//        System.out.println(foo.toDataString());

        final HierarchicalStack tier7Stack = HierarchicalStack.fromJson(TIER_STACK_007);

        final AffineWarpField warpField = new AffineWarpField(tier7Stack.getTotalTierFullScaleWidth(),
                                                              tier7Stack.getTotalTierFullScaleHeight(),
                                                              tier7Stack.getTotalTierRowCount(),
                                                              tier7Stack.getTotalTierColumnCount(),
                                                              AffineWarpField.getDefaultInterpolatorFactory());

        final double[] stack4AffineData = null; // use consensus set data for stack 000004
        setUpWarpField(tier4Stack.getScale(), stack4AffineData, warpField);

        final Map<HierarchicalStack, AffineWarpField> tierStackToConsensusFieldMap = new HashMap<>();
        tierStackToConsensusFieldMap.put(tier4Stack, consensusField);

        LOG.info("consensus debug json: {}", consensusField.toDebugJson());

        final Bounds parentBounds = new Bounds(36801.0, 38528.0, 2213.0, 47992.0, 49489.0, 2215.0);
        final double[] locationOffsets = new double[] { parentBounds.getMinX(), parentBounds.getMinY() };
        final String warpFieldTransformId = "2214.0_AFFINE_WARP_FIELD";
        final TransformSpec warpTransformSpec = ConsensusWarpFieldBuilder.buildSimpleWarpFieldTransformSpec(warpField,
                                                                                                            tierStackToConsensusFieldMap,
                                                                                                            locationOffsets,
                                                                                                            warpFieldTransformId);

        final AffineWarpFieldTransform mergedWarpFieldTransform = (AffineWarpFieldTransform) warpTransformSpec.getNewInstance();
        LOG.info("warp debug json: {}", mergedWarpFieldTransform.toDebugJson());

        // ----------------------------------------------------------------------
        // render results ...

        final RenderParameters box4Parameters =
                RenderParameters.parseJson(new File("/Users/trautmane/projects/git/render/render-app/src/test/resources/warp-field-test/box4.json"));
        final RenderParameters box7Parameters =
                RenderParameters.parseJson(new File("/Users/trautmane/projects/git/render/render-app/src/test/resources/warp-field-test/box7.json"));
        final List<TileSpec> box4And7Tiles = box7Parameters.getTileSpecs();
        box4And7Tiles.addAll(box4Parameters.getTileSpecs());

        double minX = Double.MAX_VALUE;
        double minY = Double.MAX_VALUE;
        double maxX = -Double.MAX_VALUE;
        double maxY = -Double.MAX_VALUE;
        for (final TileSpec tileSpec : box4And7Tiles) {
            tileSpec.addTransformSpecs(Collections.singletonList(warpTransformSpec));
            tileSpec.deriveBoundingBox(tileSpec.getMeshCellSize(), true, false);
            minX = Math.min(minX, tileSpec.getMinX());
            minY = Math.min(minY, tileSpec.getMinY());
            maxX = Math.max(maxX, tileSpec.getMaxX());
            maxY = Math.max(maxY, tileSpec.getMaxY());
        }

        final int margin = 10;
        final double x = minX - margin;
        final double y = minY - margin;
        final int width = (int) (maxX - minX + 1) + (margin * 2);
        final int height = (int) (maxY - minY + 1) + (margin * 2);

        final RenderParameters renderParameters = new RenderParameters(null, x, y, width, height, tier7Stack.getScale());
        box4And7Tiles.forEach(renderParameters::addTileSpec);

        final BufferedImage targetImage = renderParameters.openTargetImage();
        renderParameters.setAddWarpFieldDebugOverlay(true);
        ArgbRenderer.render(renderParameters, targetImage, ImageProcessorCache.DISABLED_CACHE);
        final ImagePlus ipWarpedBox4And7 = new ImagePlus("", targetImage);
        final FileSaver fileSaver = new FileSaver(ipWarpedBox4And7);
        fileSaver.saveAsJpeg("/Users/trautmane/Desktop/ipWarpedBox4And7_" + new Date().getTime() + ".jpg");

        //ipWarpedBox4And7.show();
    }
 
Example #8
Source File: Save3dTIFF.java    From SPIM_Registration with GNU General Public License v2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
public <T extends RealType<T> & NativeType<T>> boolean exportImage( final RandomAccessibleInterval<T> img, final BoundingBoxGUI bb, final TimePoint tp, final ViewSetup vs, final double min, final double max )
{
	// do nothing in case the image is null
	if ( img == null )
		return false;
	
	// determine min and max
	final float[] minmax;
	
	if ( Double.isNaN( min ) || Double.isNaN( max ) )
		minmax = FusionHelper.minMax( img );
	else
		minmax = new float[]{ (float)min, (float)max };

	ImagePlus imp = null;
	
	if ( img instanceof ImagePlusImg )
		try { imp = ((ImagePlusImg<T, ?>)img).getImagePlus(); } catch (ImgLibException e) {}

	if ( imp == null )
		imp = ImageJFunctions.wrap( img, getImgTitler().getImageTitle( tp, vs ) ).duplicate();

	imp.setTitle( getImgTitler().getImageTitle( tp, vs ) );

	if ( bb != null )
	{
		imp.getCalibration().xOrigin = -(bb.min( 0 ) / bb.getDownSampling());
		imp.getCalibration().yOrigin = -(bb.min( 1 ) / bb.getDownSampling());
		imp.getCalibration().zOrigin = -(bb.min( 2 ) / bb.getDownSampling());
		imp.getCalibration().pixelWidth = imp.getCalibration().pixelHeight = imp.getCalibration().pixelDepth = bb.getDownSampling();
	}
	
	imp.setDimensions( 1, (int)img.dimension( 2 ), 1 );
	
	imp.setDisplayRange( minmax[ 0 ], minmax[ 1 ] );
	
	imp.updateAndDraw();

	final String fileName;
	
	if ( !getImgTitler().getImageTitle( tp, vs ).endsWith( ".tif" ) )
		fileName = new File( path, getImgTitler().getImageTitle( tp, vs ) + ".tif" ).getAbsolutePath();
	else
		fileName = new File( path, getImgTitler().getImageTitle( tp, vs ) ).getAbsolutePath();
	
	if ( compress )
	{
		IOFunctions.println( new Date( System.currentTimeMillis() ) + ": Saving file " + fileName + ".zip" );
		return new FileSaver( imp ).saveAsZip( fileName );
	}
	else
	{
		IOFunctions.println( new Date( System.currentTimeMillis() ) + ": Saving file " + fileName );
		return new FileSaver( imp ).saveAsTiffStack( fileName );
	}
}
 
Example #9
Source File: Saver.java    From TrakEM2 with GNU General Public License v3.0 4 votes vote down vote up
JPEGSaver() {
	super();
	super.q = FileSaver.getJpegQuality() / 100.0f;
}
 
Example #10
Source File: Saver.java    From TrakEM2 with GNU General Public License v3.0 4 votes vote down vote up
@Override
boolean save(final ImagePlus imp, final String path) {
	return (ImageSaver.checkPath(path) && new FileSaver(imp).saveAsPng(path));
}
 
Example #11
Source File: Saver.java    From TrakEM2 with GNU General Public License v3.0 4 votes vote down vote up
@Override
boolean save(final ImagePlus imp, final String path) {
	return (ImageSaver.checkPath(path) && new FileSaver(imp).saveAsTiff(path));
}
 
Example #12
Source File: Saver.java    From TrakEM2 with GNU General Public License v3.0 4 votes vote down vote up
@Override
boolean save(final ImagePlus imp, final String path) {
	return (ImageSaver.checkPath(path) && new FileSaver(imp).saveAsZip(path));
}