You are viewing a plain text version of this content. The canonical link for it is here.
Posted to fop-users@xmlgraphics.apache.org by Oliver Hernàndez Valls <oh...@notariado.org> on 2006/09/08 11:04:22 UTC

outputting TIFF-G images

Hi all,
	I'm working with fop to generate MTIFF text images. At the moment i'm 
using fop-trunk because no justification functionality is working in fop 
0.92 for tiffs.
	Right now I've all the functionality to generate parametrized text 
images implemented. By default fop uses packbits compression and colored 
image coding.
	I'd like to change the tiff coding to TIFF-G because generated images 
with the default tiff coding are very big (around 9000 kB) and 
coloration is not needed for the images I'm generating.
	I'm using the "new" FOUserAgent parameter setTargetResolution(int), but 
I can't see any way to change the default encoding for tiff images.
	Some time ago I readed this somewhere in the source code: "//TODO 
Support output of monochrome bitmaps (fax-style)", but don't know if it 
has something to do with changing tiff coding.

	Any hint/workarround/documentation please?

Thanks a lot, salut / cheers !

---------------------------------------------------------------------
To unsubscribe, e-mail: fop-users-unsubscribe@xmlgraphics.apache.org
For additional commands, e-mail: fop-users-help@xmlgraphics.apache.org


Re: outputting TIFF-G images

Posted by Jeremias Maerki <de...@jeremias-maerki.ch>.
On 13.09.2006 13:51:35 Oliver Hernàndez Valls wrote:
> Sorry if these questions are too obvious.
> 
> 
> En/na Jeremias Maerki ha escrit:
> > One more thing: The TIFFRenderer currently uses the internal codecs from
> > XML Graphics Commons to encode TIFF images. 
> 
> I understand you are talking about 
> org.apache.xmlgraphics.image.codec.tiff.TIFFImageEncoder in the method 
> stopRenderer()

Yes.

> These do not support writing
> > CCITT-G4 encoded images. We could switch to the ImageWriters I wrote for
> > Batik and which are now available in XML Graphics Commons. They allow an
> > abstraction from the underlying codec for image writing. There are
> > implementations of the ImageWriter that write images through ImageIO
> 
> ImageIOTIFFImageWriter?

That's only an implementation. I'm talking about the ImageWriter
interface in general. You don't access implementations of the interface
directly but only get an ImageWriter interface through the
ImageWriterRegistry. The problem: FOP requires JDK 1.3 and ImageIO is
not available there. In that case we still need to use the "internal
codecs" (with not CCITT compression capability). In JDK >= 1.4
(including GNU Classpath based VMs) we'll use ImageIO and have TIFF
capabilities when using the JAI ImageIO Tools.

> > which might have CCITT-capable codecs available but the code will have
> > to be extended to choose the compression algorithm. 
> 
> So you're talking about subclassing ImageIOTIFFImageWriter (into batik 
> or into fop?) or adding code into? to use, for example, TIFFFaxDecoder?

No, maybe adjusting/improving the ImageIOTIFFImageWriter if it doesn't
do the right things, yet. I'm going to write some example code later
today that explains what I mean.


> All in all, no easy
> > solution to your requirement but certainly not much more than half a day
> > of work.
> > 
> > On 10.09.2006 12:54:46 Jeremias Maerki wrote:
> >> There's a configuration value you can set to modify the compression used
> >> but it's poorly designed (requiring an integer value) and undocumented.
> >> Furthermore, it does not support setting CCITT-G4 compression.
> >> Generating monochrome (1bit) images has also not been implemented, yet.
> >>
> >> To implement all this, changes would have to be made in:
> >> - Java2DRenderer.getPageImage(): Extract code into a protected method to
> >> instantiate the BufferedImage that we paint on. Right now, it always
> >> allocates an 24 bit RGB image with an 8-bit alpha channel.
> 
> OK
> 
> >> - TIFFRenderer.LazyPageImagesIterator.next(): Code to handle 1bit images.
> 
> Uncoment the code for TIFFEncodeParam.COMPRESSION_GROUP4? simply return 
> the BufferedImage generated in the protected method above (I think is 
> this one)? or some other hack?

Yes, it could be as simple as that. Not sure, though.

> >> - TIFFRenderer.configure(): provide better configuration using names for
> >> compression methods.
> 
> What does this method does or have to do? I don't undertand why this 
> method exists. It's reason is to log the compression?

The configure() method is used to configure Renderer instances from the
FOP user configuration file. You can then set the compression method in
the configuration file and you don't have to instantiate and configure the
renderer yourself.

> >> - Override the new protected method described above to create the
> >> Buffered image depending on the configuration.
> 
> OK
> 
> >>
> >> If you don't want to hack FOP code, the work-around is to convert the
> >> generated TIFF file after generation to CCITT format somehow. Obvious,
> >> isn't it? :-)
> >>
> >> On 08.09.2006 11:04:22 Oliver Hernàndez Valls wrote:
> >>> Hi all,
> >>> 	I'm working with fop to generate MTIFF text images. At the moment i'm 
> >>> using fop-trunk because no justification functionality is working in fop 
> >>> 0.92 for tiffs.
> >>> 	Right now I've all the functionality to generate parametrized text 
> >>> images implemented. By default fop uses packbits compression and colored 
> >>> image coding.
> >>> 	I'd like to change the tiff coding to TIFF-G because generated images 
> >>> with the default tiff coding are very big (around 9000 kB) and 
> >>> coloration is not needed for the images I'm generating.
> >>> 	I'm using the "new" FOUserAgent parameter setTargetResolution(int), but 
> >>> I can't see any way to change the default encoding for tiff images.
> >>> 	Some time ago I readed this somewhere in the source code: "//TODO 
> >>> Support output of monochrome bitmaps (fax-style)", but don't know if it 
> >>> has something to do with changing tiff coding.
> >>>
> >>> 	Any hint/workarround/documentation please?


Jeremias Maerki


---------------------------------------------------------------------
To unsubscribe, e-mail: fop-users-unsubscribe@xmlgraphics.apache.org
For additional commands, e-mail: fop-users-help@xmlgraphics.apache.org


Re: outputting TIFF-G images

Posted by Jeremias Maerki <de...@jeremias-maerki.ch>.
Sorry for not being more reponsive. I'm quite busy outside of FOP lately.

You can get TIFF support for ImageIO by downloading and installing (see
docs) JAI ImageIO Tools: http://java.sun.com/products/java-media/jai/downloads/download-iio-1_0_01.html

Would you please do me a favor and open an issue in Bugzilla
(http://issues.apache.org/bugzilla) and add patches (not full Java files)
there as is described here?
http://xmlgraphics.apache.org/fop/dev/index.html#patches

Thanks. I'll take a look at your work so far shortly.

On 14.09.2006 18:05:46 Oliver Hernàndez Valls wrote:
> I keep trying to make the TIFFRenderer work with CCITT T.6 bilevel 
> compression (CCITT Group 4 facsimile compression). But can't make it work.
> 
> When the outputStream flushes I have this exception:
> Caused by: java.util.NoSuchElementException
> 	at javax.imageio.spi.FilterIterator.next(ServiceRegistry.java:808)
> 	at javax.imageio.ImageIO$ImageWriterIterator.next(ImageIO.java:820)
> 	at javax.imageio.ImageIO$ImageWriterIterator.next(ImageIO.java:805)
> 	at 
> org.apache.xmlgraphics.image.writer.imageio.ImageIOImageWriter.writeImage(ImageIOImageWriter.java:73)
> 	at 
> org.apache.fop.render.bitmap.TIFFRenderer.stopRenderer(TIFFRenderer.java:196)
> 	at 
> org.apache.fop.area.RenderPagesModel.endDocument(RenderPagesModel.java:240)
> 	at 
> org.apache.fop.area.AreaTreeHandler.endDocument(AreaTreeHandler.java:422)
> 	at org.apache.fop.fo.FOTreeBuilder.endDocument(FOTreeBuilder.java:170)
> 	at 
> org.apache.xml.serializer.ToXMLSAXHandler.endDocument(ToXMLSAXHandler.java:182)
> 	at 
> org.apache.xalan.transformer.TransformerImpl.transformNode(TransformerImpl.java:1287)
> 	... 43 more
> 
> 	I think the problem I have is that the IIORegistry has no service 
> providers for image/tiff mime types. And I don't know how to register 
> one. Neither I know where to find one.
> 	Does somebody know how to make IIORegistry provide an encoder for tiff 
> images??
> 
> thanks a lot in advance!
> 
> this is the TIFFRenderer.java I have at present:
<snip/>



Jeremias Maerki


---------------------------------------------------------------------
To unsubscribe, e-mail: fop-users-unsubscribe@xmlgraphics.apache.org
For additional commands, e-mail: fop-users-help@xmlgraphics.apache.org


Re: outputting TIFF-G images

Posted by Oliver Hernàndez Valls <oh...@notariado.org>.
Hi Jeremias,
	I've been working a little with your suggestions.
	What I have done is this little work:
1 -Extract code into a protected method to instantiate the BufferedImage 
that we paint on. This methods signature is:

protected BufferedImage getBufferedImage(int bitmapWidth, int bitmapHeight)

2- Modify TIFFRenderer.configure() for selecting the BufferedImage type 
in a new attribute.

3- Override the new protected method described above to create the
Buffered image depending on the configuration.

Here you are the code:


Java2DRenderer
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/*
  * Copyright 1999-2006 The Apache Software Foundation.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
  *
  *      http://www.apache.org/licenses/LICENSE-2.0
  *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */

/* $Id: Java2DRenderer.java 410308 2006-05-30 15:53:12Z jeremias $ */

package org.apache.fop.render.java2d;

// Java
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.color.ColorSpace;
import java.awt.font.GlyphVector;
import java.awt.geom.AffineTransform;
import java.awt.geom.GeneralPath;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.ComponentColorModel;
import java.awt.image.DataBuffer;
import java.awt.image.DataBufferByte;
import java.awt.image.PixelInterleavedSampleModel;
import java.awt.image.Raster;
import java.awt.image.SampleModel;
import java.awt.image.WritableRaster;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Stack;

import org.w3c.dom.Document;

import org.apache.fop.apps.FOPException;
import org.apache.fop.apps.FOUserAgent;
import org.apache.fop.area.CTM;
import org.apache.fop.area.PageViewport;
import org.apache.fop.area.Trait;
import org.apache.fop.area.inline.Image;
import org.apache.fop.area.inline.InlineArea;
import org.apache.fop.area.inline.Leader;
import org.apache.fop.area.inline.SpaceArea;
import org.apache.fop.area.inline.TextArea;
import org.apache.fop.area.inline.WordArea;
import org.apache.fop.fo.Constants;
import org.apache.fop.fonts.Font;
import org.apache.fop.fonts.FontInfo;
import org.apache.fop.fonts.Typeface;
import org.apache.fop.image.FopImage;
import org.apache.fop.image.ImageFactory;
import org.apache.fop.image.XMLImage;
import org.apache.fop.render.AbstractPathOrientedRenderer;
import org.apache.fop.render.Graphics2DAdapter;
import org.apache.fop.render.RendererContext;
import org.apache.fop.render.pdf.CTMHelper;
import org.apache.fop.util.CharUtilities;

/**
  * The <code>Java2DRenderer</code> class provides the abstract technical
  * foundation for all rendering with the Java2D API. Renderers like
  * <code>AWTRenderer</code> subclass it and provide the concrete output 
paths.
  * <p>
  * A lot of the logic is performed by <code>AbstractRenderer</code>. The
  * class-variables <code>currentIPPosition</code> and
  * <code>currentBPPosition</code> hold the position of the currently 
rendered
  * area.
  * <p>
  * <code>Java2DGraphicsState state</code> holds the 
<code>Graphics2D</code>,
  * which is used along the whole rendering. <code>state</code> also 
acts as a
  * stack (<code>state.push()</code> and <code>state.pop()</code>).
  * <p>
  * The rendering process is basically always the same:
  * <p>
  * <code>void renderXXXXX(Area area) {
  *    //calculate the currentPosition
  *    state.updateFont(name, size, null);
  *    state.updateColor(ct, false, null);
  *    state.getGraph.draw(new Shape(args));
  * }</code>
  *
  */
public abstract class Java2DRenderer extends 
AbstractPathOrientedRenderer implements Printable {

     /** The scale factor for the image size, values: ]0 ; 1] */
     protected double scaleFactor = 1;

     /** The page width in pixels */
     protected int pageWidth = 0;

     /** The page height in pixels */
     protected int pageHeight = 0;

     /** List of Viewports */
     protected List pageViewportList = new java.util.ArrayList();

     /** The 0-based current page number */
     private int currentPageNumber = 0;

     /** The 0-based total number of rendered pages */
     private int numberOfPages;

     /** true if antialiasing is set */
     protected boolean antialiasing = true;

     /** true if qualityRendering is set */
     protected boolean qualityRendering = true;

     /** The current state, holds a Graphics2D and its context */
     protected Java2DGraphicsState state;

     private Stack stateStack = new Stack();

     /** true if the renderer has finished rendering all the pages */
     private boolean renderingDone;

     private GeneralPath currentPath = null;

     /** Default constructor */
     public Java2DRenderer() {
     }

     /**
      * @see 
org.apache.fop.render.Renderer#setUserAgent(org.apache.fop.apps.FOUserAgent)
      */
     public void setUserAgent(FOUserAgent foUserAgent) {
         super.setUserAgent(foUserAgent);
         userAgent.setRendererOverride(this); // for document regeneration
     }

     /** @return the FOUserAgent */
     public FOUserAgent getUserAgent() {
         return userAgent;
     }

     /**
      * @see 
org.apache.fop.render.Renderer#setupFontInfo(org.apache.fop.fonts.FontInfo)
      */
     public void setupFontInfo(FontInfo inFontInfo) {
         //Don't call super.setupFontInfo() here! Java2D needs a special 
font setup
         // create a temp Image to test font metrics on
         fontInfo = inFontInfo;
         BufferedImage fontImage = new BufferedImage(100, 100,
                 BufferedImage.TYPE_INT_RGB);
         Graphics2D g = fontImage.createGraphics();
         //The next line is important to get accurate font metrics!
         g.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS,
                 RenderingHints.VALUE_FRACTIONALMETRICS_ON);
         FontSetup.setup(fontInfo, g);
     }

     /** @see org.apache.fop.render.Renderer#getGraphics2DAdapter() */
     public Graphics2DAdapter getGraphics2DAdapter() {
         return new Java2DGraphics2DAdapter(state);
     }

     /**
      * Sets the new scale factor.
      * @param newScaleFactor ]0 ; 1]
      */
     public void setScaleFactor(double newScaleFactor) {
         scaleFactor = newScaleFactor;
     }

     /** @return the scale factor */
     public double getScaleFactor() {
         return scaleFactor;
     }

     /** @see 
org.apache.fop.render.Renderer#startRenderer(java.io.OutputStream) */
     public void startRenderer(OutputStream out) throws IOException {
         // do nothing by default
     }

     /** @see org.apache.fop.render.Renderer#stopRenderer() */
     public void stopRenderer() throws IOException {
         log.debug("Java2DRenderer stopped");
         renderingDone = true;
         numberOfPages = currentPageNumber;
         // TODO set all vars to null for gc
         if (numberOfPages == 0) {
             new FOPException("No page could be rendered");
         }
     }

     /** @return true if the renderer is not currently processing */
     public boolean isRenderingDone() {
         return this.renderingDone;
     }

     /**
      * @return The 0-based current page number
      */
     public int getCurrentPageNumber() {
         return currentPageNumber;
     }

     /**
      * @param c the 0-based current page number
      */
     public void setCurrentPageNumber(int c) {
         this.currentPageNumber = c;
     }

     /**
      * @return The 0-based total number of rendered pages
      */
     public int getNumberOfPages() {
             return numberOfPages;
     }

     /**
      * Clears the ViewportList.
      * Used if the document is reloaded.
      */
     public void clearViewportList() {
         pageViewportList.clear();
         setCurrentPageNumber(0);
     }

     /**
      * This method override only stores the PageViewport in a List. No 
actual
      * rendering is performed here. A renderer override renderPage() to 
get the
      * freshly produced PageViewport, and rendere them on the fly 
(producing the
      * desired BufferedImages by calling getPageImage(), which lazily 
starts the
      * rendering process).
      *
      * @param pageViewport the <code>PageViewport</code> object supplied by
      * the Area Tree
      * @throws IOException In case of an I/O error
      * @see org.apache.fop.render.Renderer
      */
     public void renderPage(PageViewport pageViewport) throws IOException {
         // TODO clone?
         pageViewportList.add(pageViewport.clone());
         currentPageNumber++;
     }

     /**
      * Generates a desired page from the renderer's page viewport list.
      *
      * @param pageViewport the PageViewport to be rendered
      * @return the <code>java.awt.image.BufferedImage</code> 
corresponding to
      * the page or null if the page doesn't exist.
      */
     public BufferedImage getPageImage(PageViewport pageViewport) {

         this.currentPageViewport = pageViewport;
         try {
             Rectangle2D bounds = pageViewport.getViewArea();
             pageWidth = (int) Math.round(bounds.getWidth() / 1000f);
             pageHeight = (int) Math.round(bounds.getHeight() / 1000f);

             log.info(
                     "Rendering Page " + pageViewport.getPageNumberString()
                             + " (pageWidth " + pageWidth + ", pageHeight "
                             + pageHeight + ")");

             double scaleX = scaleFactor
                 * (25.4 / FOUserAgent.DEFAULT_TARGET_RESOLUTION)
                 / userAgent.getTargetPixelUnitToMillimeter();
             double scaleY = scaleFactor
                 * (25.4 / FOUserAgent.DEFAULT_TARGET_RESOLUTION)
                 / userAgent.getTargetPixelUnitToMillimeter();
             int bitmapWidth = (int) ((pageWidth * scaleX) + 0.5);
             int bitmapHeight = (int) ((pageHeight * scaleY) + 0.5);


             BufferedImage currentPageImage = 
getBufferedImage(bitmapWidth, bitmapHeight);

             Graphics2D graphics = currentPageImage.createGraphics();
             graphics.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS,
                     RenderingHints.VALUE_FRACTIONALMETRICS_ON);
             if (antialiasing) {
                 graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                         RenderingHints.VALUE_ANTIALIAS_ON);
 
graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
                         RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
             }
             if (qualityRendering) {
                 graphics.setRenderingHint(RenderingHints.KEY_RENDERING,
                         RenderingHints.VALUE_RENDER_QUALITY);
             }

             // transform page based on scale factor supplied
             AffineTransform at = graphics.getTransform();
             at.scale(scaleX, scaleY);
             graphics.setTransform(at);

             // draw page frame
             graphics.setColor(Color.white);
             graphics.fillRect(0, 0, pageWidth, pageHeight);
             graphics.setColor(Color.black);
             graphics.drawRect(-1, -1, pageWidth + 2, pageHeight + 2);
             graphics.drawLine(pageWidth + 2, 0, pageWidth + 2, 
pageHeight + 2);
             graphics.drawLine(pageWidth + 3, 1, pageWidth + 3, 
pageHeight + 3);
             graphics.drawLine(0, pageHeight + 2, pageWidth + 2, 
pageHeight + 2);
             graphics.drawLine(1, pageHeight + 3, pageWidth + 3, 
pageHeight + 3);

             state = new Java2DGraphicsState(graphics, this.fontInfo, at);
             try {
                 // reset the current Positions
                 currentBPPosition = 0;
                 currentIPPosition = 0;

                 // this toggles the rendering of all areas
                 renderPageAreas(pageViewport.getPage());
             } finally {
                 state = null;
             }

             return currentPageImage;
         } finally {
             this.currentPageViewport = null;
         }
     }

     /**
      * Returns a specific <coede>BufferedImage</code> depending on this 
<code>Java2DRenderer</code>
      * implementation configuration.
      * <p>
      * Override this method to obtain other types of BufferedImage.
      *
      * @param bitmapWidth
      * @param bitmapHeight
      * @return
      */
     protected BufferedImage getBufferedImage(int bitmapWidth, int 
bitmapHeight)
     {
     	return new BufferedImage(
                 bitmapWidth, bitmapHeight, BufferedImage.TYPE_INT_ARGB);
     }

	/**
      * Returns a page viewport.
      * @param pageNum the page number
      * @return the requested PageViewport instance
      * @exception FOPException If the page is out of range.
      */
     public PageViewport getPageViewport(int pageNum) throws FOPException {
         if (pageNum < 0 || pageNum >= pageViewportList.size()) {
             throw new FOPException("Requested page number is out of 
range: " + pageNum
                      + "; only " + pageViewportList.size()
                      + " page(s) available.");
         }
         return (PageViewport) pageViewportList.get(pageNum);
     }

     /**
      * Generates a desired page from the renderer's page viewport list.
      *
      * @param pageNum the 0-based page number to generate
      * @return the <code>java.awt.image.BufferedImage</code> 
corresponding to
      * the page or null if the page doesn't exist.
      * @throws FOPException If there's a problem preparing the page image
      */
     public BufferedImage getPageImage(int pageNum) throws FOPException {
         return getPageImage(getPageViewport(pageNum));
     }

     /** Saves the graphics state of the rendering engine. */
     protected void saveGraphicsState() {
         // push (and save) the current graphics state
         stateStack.push(state);
         state = new Java2DGraphicsState(state);
     }

     /** Restores the last graphics state of the rendering engine. */
     protected void restoreGraphicsState() {
         state.dispose();
         state = (Java2DGraphicsState)stateStack.pop();
     }

     /**
      * @see org.apache.fop.render.AbstractRenderer#startVParea(CTM, 
Rectangle2D)
      */
     protected void startVParea(CTM ctm, Rectangle2D clippingRect) {

         saveGraphicsState();

         if (clippingRect != null) {
             clipRect((float)clippingRect.getX() / 1000f,
                     (float)clippingRect.getY() / 1000f,
                     (float)clippingRect.getWidth() / 1000f,
                     (float)clippingRect.getHeight() / 1000f);
         }

         // Set the given CTM in the graphics state
         //state.setTransform(new 
AffineTransform(CTMHelper.toPDFArray(ctm)));
         state.transform(new AffineTransform(CTMHelper.toPDFArray(ctm)));
     }

     /**
      * @see org.apache.fop.render.AbstractRenderer#endVParea()
      */
     protected void endVParea() {
         restoreGraphicsState();
     }

     /**
      * @see 
org.apache.fop.render.AbstractPathOrientedRenderer#breakOutOfStateStack()
      */
     protected List breakOutOfStateStack() {
         log.debug("Block.FIXED --> break out");
         List breakOutList;
         breakOutList = new java.util.ArrayList();
         while (!stateStack.isEmpty()) {
             breakOutList.add(0, state);
             //We only pop, we don't dispose, because we can use the 
instances again later
             state = (Java2DGraphicsState)stateStack.pop();
         }
         return breakOutList;
     }

     /**
      * @see 
org.apache.fop.render.AbstractPathOrientedRenderer#restoreStateStackAfterBreakOut(
      *          java.util.List)
      */
     protected void restoreStateStackAfterBreakOut(List breakOutList) {
         log.debug("Block.FIXED --> restoring context after break-out");

         Iterator i = breakOutList.iterator();
         while (i.hasNext()) {
             Java2DGraphicsState s = (Java2DGraphicsState)i.next();
             stateStack.push(state);
             state = s;
         }
     }

     /**
      * @see org.apache.fop.render.AbstractPathOrientedRenderer#updateColor(
      *          org.apache.fop.datatypes.ColorType, boolean)
      */
     protected void updateColor(Color col, boolean fill) {
         state.updateColor(col);
     }

     /**
      * @see org.apache.fop.render.AbstractPathOrientedRenderer#clip()
      */
     protected void clip() {
         if (currentPath == null) {
             throw new IllegalStateException("No current path available!");
         }
         state.updateClip(currentPath);
         currentPath = null;
     }

     /**
      * @see org.apache.fop.render.AbstractPathOrientedRenderer#closePath()
      */
     protected void closePath() {
         currentPath.closePath();
     }

     /**
      * @see 
org.apache.fop.render.AbstractPathOrientedRenderer#lineTo(float, float)
      */
     protected void lineTo(float x, float y) {
         if (currentPath == null) {
             currentPath = new GeneralPath();
         }
         currentPath.lineTo(x, y);
     }

     /**
      * @see 
org.apache.fop.render.AbstractPathOrientedRenderer#moveTo(float, float)
      */
     protected void moveTo(float x, float y) {
         if (currentPath == null) {
             currentPath = new GeneralPath();
         }
         currentPath.moveTo(x, y);
     }

     /**
      * @see 
org.apache.fop.render.AbstractPathOrientedRenderer#clipRect(float, 
float, float, float)
      */
     protected void clipRect(float x, float y, float width, float height) {
         state.updateClip(new Rectangle2D.Float(x, y, width, height));
     }

     /**
      * @see 
org.apache.fop.render.AbstractPathOrientedRenderer#fillRect(float, 
float, float, float)
      */
     protected void fillRect(float x, float y, float width, float height) {
         state.getGraph().fill(new Rectangle2D.Float(x, y, width, height));
     }

     /**
      * @see 
org.apache.fop.render.AbstractPathOrientedRenderer#drawBorderLine(
      *          float, float, float, float, boolean, boolean, int,
      *          org.apache.fop.datatypes.ColorType)
      */
     protected void drawBorderLine(float x1, float y1, float x2, float y2,
             boolean horz, boolean startOrBefore, int style, Color col) {
         Graphics2D g2d = state.getGraph();
         drawBorderLine(new Rectangle2D.Float(x1, y1, x2 - x1, y2 - y1),
                 horz, startOrBefore, style, col, g2d);
     }

     /**
      * Draw a border segment of an XSL-FO style border.
      * @param lineRect the line defined by its bounding rectangle
      * @param horz true for horizontal border segments, false for 
vertical border segments
      * @param startOrBefore true for border segments on the start or 
before edge,
      *                      false for end or after.
      * @param style the border style (one of Constants.EN_DASHED etc.)
      * @param col the color for the border segment
      * @param g2d the Graphics2D instance to paint to
      */
     public static void drawBorderLine(Rectangle2D.Float lineRect,
             boolean horz, boolean startOrBefore, int style, Color col, 
Graphics2D g2d) {
         float x1 = lineRect.x;
         float y1 = lineRect.y;
         float x2 = x1 + lineRect.width;
         float y2 = y1 + lineRect.height;
         float w = lineRect.width;
         float h = lineRect.height;
         if ((w < 0) || (h < 0)) {
             log.error("Negative extent received. Border won't be 
painted.");
             return;
         }
         switch (style) {
             case Constants.EN_DASHED:
                 g2d.setColor(col);
                 if (horz) {
                     float unit = Math.abs(2 * h);
                     int rep = (int)(w / unit);
                     if (rep % 2 == 0) {
                         rep++;
                     }
                     unit = w / rep;
                     float ym = y1 + (h / 2);
                     BasicStroke s = new BasicStroke(h, 
BasicStroke.CAP_BUTT,
                             BasicStroke.JOIN_MITER, 10.0f, new float[] 
{unit}, 0);
                     g2d.setStroke(s);
                     g2d.draw(new Line2D.Float(x1, ym, x2, ym));
                 } else {
                     float unit = Math.abs(2 * w);
                     int rep = (int)(h / unit);
                     if (rep % 2 == 0) {
                         rep++;
                     }
                     unit = h / rep;
                     float xm = x1 + (w / 2);
                     BasicStroke s = new BasicStroke(w, 
BasicStroke.CAP_BUTT,
                             BasicStroke.JOIN_MITER, 10.0f, new float[] 
{unit}, 0);
                     g2d.setStroke(s);
                     g2d.draw(new Line2D.Float(xm, y1, xm, y2));
                 }
                 break;
             case Constants.EN_DOTTED:
                 g2d.setColor(col);
                 if (horz) {
                     float unit = Math.abs(2 * h);
                     int rep = (int)(w / unit);
                     if (rep % 2 == 0) {
                         rep++;
                     }
                     unit = w / rep;
                     float ym = y1 + (h / 2);
                     BasicStroke s = new BasicStroke(h, 
BasicStroke.CAP_ROUND,
                             BasicStroke.JOIN_MITER, 10.0f, new float[] 
{0, unit}, 0);
                     g2d.setStroke(s);
                     g2d.draw(new Line2D.Float(x1, ym, x2, ym));
                 } else {
                     float unit = Math.abs(2 * w);
                     int rep = (int)(h / unit);
                     if (rep % 2 == 0) {
                         rep++;
                     }
                     unit = h / rep;
                     float xm = x1 + (w / 2);
                     BasicStroke s = new BasicStroke(w, 
BasicStroke.CAP_ROUND,
                             BasicStroke.JOIN_MITER, 10.0f, new float[] 
{0, unit}, 0);
                     g2d.setStroke(s);
                     g2d.draw(new Line2D.Float(xm, y1, xm, y2));
                 }
                 break;
             case Constants.EN_DOUBLE:
                 g2d.setColor(col);
                 if (horz) {
                     float h3 = h / 3;
                     float ym1 = y1 + (h3 / 2);
                     float ym2 = ym1 + h3 + h3;
                     BasicStroke s = new BasicStroke(h3);
                     g2d.setStroke(s);
                     g2d.draw(new Line2D.Float(x1, ym1, x2, ym1));
                     g2d.draw(new Line2D.Float(x1, ym2, x2, ym2));
                 } else {
                     float w3 = w / 3;
                     float xm1 = x1 + (w3 / 2);
                     float xm2 = xm1 + w3 + w3;
                     BasicStroke s = new BasicStroke(w3);
                     g2d.setStroke(s);
                     g2d.draw(new Line2D.Float(xm1, y1, xm1, y2));
                     g2d.draw(new Line2D.Float(xm2, y1, xm2, y2));
                 }
                 break;
             case Constants.EN_GROOVE:
             case Constants.EN_RIDGE:
                 float colFactor = (style == EN_GROOVE ? 0.4f : -0.4f);
                 if (horz) {
                     Color uppercol = lightenColor(col, -colFactor);
                     Color lowercol = lightenColor(col, colFactor);
                     float h3 = h / 3;
                     float ym1 = y1 + (h3 / 2);
                     g2d.setStroke(new BasicStroke(h3));
                     g2d.setColor(uppercol);
                     g2d.draw(new Line2D.Float(x1, ym1, x2, ym1));
                     g2d.setColor(col);
                     g2d.draw(new Line2D.Float(x1, ym1 + h3, x2, ym1 + h3));
                     g2d.setColor(lowercol);
                     g2d.draw(new Line2D.Float(x1, ym1 + h3 + h3, x2, 
ym1 + h3 + h3));
                 } else {
                     Color leftcol = lightenColor(col, -colFactor);
                     Color rightcol = lightenColor(col, colFactor);
                     float w3 = w / 3;
                     float xm1 = x1 + (w3 / 2);
                     g2d.setStroke(new BasicStroke(w3));
                     g2d.setColor(leftcol);
                     g2d.draw(new Line2D.Float(xm1, y1, xm1, y2));
                     g2d.setColor(col);
                     g2d.draw(new Line2D.Float(xm1 + w3, y1, xm1 + w3, y2));
                     g2d.setColor(rightcol);
                     g2d.draw(new Line2D.Float(xm1 + w3 + w3, y1, xm1 + 
w3 + w3, y2));
                 }
                 break;
             case Constants.EN_INSET:
             case Constants.EN_OUTSET:
                 colFactor = (style == EN_OUTSET ? 0.4f : -0.4f);
                 if (horz) {
                     col = lightenColor(col, (startOrBefore ? 1 : -1) * 
colFactor);
                     g2d.setStroke(new BasicStroke(h));
                     float ym1 = y1 + (h / 2);
                     g2d.setColor(col);
                     g2d.draw(new Line2D.Float(x1, ym1, x2, ym1));
                 } else {
                     col = lightenColor(col, (startOrBefore ? 1 : -1) * 
colFactor);
                     float xm1 = x1 + (w / 2);
                     g2d.setStroke(new BasicStroke(w));
                     g2d.setColor(col);
                     g2d.draw(new Line2D.Float(xm1, y1, xm1, y2));
                 }
                 break;
             case Constants.EN_HIDDEN:
                 break;
             default:
                 g2d.setColor(col);
                 if (horz) {
                     float ym = y1 + (h / 2);
                     g2d.setStroke(new BasicStroke(h));
                     g2d.draw(new Line2D.Float(x1, ym, x2, ym));
                 } else {
                     float xm = x1 + (w / 2);
                     g2d.setStroke(new BasicStroke(w));
                     g2d.draw(new Line2D.Float(xm, y1, xm, y2));
                 }
         }
     }

     /**
      * @see org.apache.fop.render.AbstractRenderer#renderText(TextArea)
      */
     public void renderText(TextArea text) {
         renderInlineAreaBackAndBorders(text);

         int rx = currentIPPosition + text.getBorderAndPaddingWidthStart();
         int bl = currentBPPosition + text.getOffset() + 
text.getBaselineOffset();
         int saveIP = currentIPPosition;

         Font font = getFontFromArea(text);
         state.updateFont(font.getFontName(), font.getFontSize());
         saveGraphicsState();
         AffineTransform at = new AffineTransform();
         at.translate(rx / 1000f, bl / 1000f);
         state.transform(at);
         renderText(text, state.getGraph(), font);
         restoreGraphicsState();

         currentIPPosition = saveIP + text.getAllocIPD();
         //super.renderText(text);

         // rendering text decorations
         Typeface tf = (Typeface) 
fontInfo.getFonts().get(font.getFontName());
         int fontsize = text.getTraitAsInteger(Trait.FONT_SIZE);
         renderTextDecoration(tf, fontsize, text, bl, rx);
     }

     /**
      * Renders a TextArea to a Graphics2D instance. Adjust the 
coordinate system so that the
      * start of the baseline of the first character is at coordinate (0,0).
      * @param text the TextArea
      * @param g2d the Graphics2D to render to
      * @param font the font to paint with
      */
     public static void renderText(TextArea text, Graphics2D g2d, Font 
font) {

         Color col = (Color) text.getTrait(Trait.COLOR);
         g2d.setColor(col);

         float textCursor = 0;

         Iterator iter = text.getChildAreas().iterator();
         while (iter.hasNext()) {
             InlineArea child = (InlineArea)iter.next();
             if (child instanceof WordArea) {
                 WordArea word = (WordArea)child;
                 String s = word.getWord();
                 int[] letterAdjust = word.getLetterAdjustArray();
                 GlyphVector gv = 
g2d.getFont().createGlyphVector(g2d.getFontRenderContext(), s);
                 double additionalWidth = 0.0;
                 if (letterAdjust == null
                         && text.getTextLetterSpaceAdjust() == 0
                         && text.getTextWordSpaceAdjust() == 0) {
                     //nop
                 } else {
                     int[] offsets = getGlyphOffsets(s, font, text, 
letterAdjust);
                     float cursor = 0.0f;
                     for (int i = 0; i < offsets.length; i++) {
                         Point2D pt = gv.getGlyphPosition(i);
                         pt.setLocation(cursor, pt.getY());
                         gv.setGlyphPosition(i, pt);
                         cursor += offsets[i] / 1000f;
                     }
                     additionalWidth = cursor - 
gv.getLogicalBounds().getWidth();
                 }
                 g2d.drawGlyphVector(gv, textCursor, 0);
                 textCursor += gv.getLogicalBounds().getWidth() + 
additionalWidth;
             } else if (child instanceof SpaceArea) {
                 SpaceArea space = (SpaceArea)child;
                 String s = space.getSpace();
                 char sp = s.charAt(0);
                 int tws = (space.isAdjustable()
                         ? text.getTextWordSpaceAdjust()
                                 + 2 * text.getTextLetterSpaceAdjust()
                         : 0);

                 textCursor += (font.getCharWidth(sp) + tws) / 1000f;
             } else {
                 throw new IllegalStateException("Unsupported child 
element: " + child);
             }
         }
     }

     private static int[] getGlyphOffsets(String s, Font font, TextArea 
text,
             int[] letterAdjust) {
         int textLen = s.length();
         int[] offsets = new int[textLen];
         for (int i = 0; i < textLen; i++) {
             final char c = s.charAt(i);
             final char mapped = font.mapChar(c);
             int wordSpace;

             if (CharUtilities.isAdjustableSpace(mapped)) {
                 wordSpace = text.getTextWordSpaceAdjust();
             } else {
                 wordSpace = 0;
             }
             int cw = font.getWidth(mapped);
             int ladj = (letterAdjust != null && i < textLen - 1 ? 
letterAdjust[i + 1] : 0);
             int tls = (i < textLen - 1 ? 
text.getTextLetterSpaceAdjust() : 0);
             offsets[i] = cw + ladj + tls + wordSpace;
         }
         return offsets;
     }

     /**
      * Render leader area. This renders a leader area which is an area 
with a
      * rule.
      *
      * @param area the leader area to render
      */
     public void renderLeader(Leader area) {
         renderInlineAreaBackAndBorders(area);

         // TODO leader-length: 25%, 50%, 75%, 100% not working yet
         // TODO Colors do not work on Leaders yet

         float startx = (currentIPPosition + 
area.getBorderAndPaddingWidthStart()) / 1000f;
         float starty = ((currentBPPosition + area.getOffset()) / 1000f);
         float endx = (currentIPPosition + 
area.getBorderAndPaddingWidthStart()
                 + area.getIPD()) / 1000f;

         Color col = (Color) area.getTrait(Trait.COLOR);
         state.updateColor(col);

         Line2D line = new Line2D.Float();
         line.setLine(startx, starty, endx, starty);
         float ruleThickness = area.getRuleThickness() / 1000f;

         int style = area.getRuleStyle();
         switch (style) {
         case EN_SOLID:
         case EN_DASHED:
         case EN_DOUBLE:
             drawBorderLine(startx, starty, endx, starty + ruleThickness,
                     true, true, style, col);
             break;
         case EN_DOTTED:
             //TODO Dots should be shifted to the left by ruleThickness / 2
             state.updateStroke(ruleThickness, style);
             float rt2 = ruleThickness / 2f;
             line.setLine(line.getX1(), line.getY1() + rt2, 
line.getX2(), line.getY2() + rt2);
             state.getGraph().draw(line);
             break;
         case EN_GROOVE:
         case EN_RIDGE:
             float half = area.getRuleThickness() / 2000f;

             state.updateColor(lightenColor(col, 0.6f));
             moveTo(startx, starty);
             lineTo(endx, starty);
             lineTo(endx, starty + 2 * half);
             lineTo(startx, starty + 2 * half);
             closePath();
             state.getGraph().fill(currentPath);
             currentPath = null;
             state.updateColor(col);
             if (style == EN_GROOVE) {
                 moveTo(startx, starty);
                 lineTo(endx, starty);
                 lineTo(endx, starty + half);
                 lineTo(startx + half, starty + half);
                 lineTo(startx, starty + 2 * half);
             } else {
                 moveTo(endx, starty);
                 lineTo(endx, starty + 2 * half);
                 lineTo(startx, starty + 2 * half);
                 lineTo(startx, starty + half);
                 lineTo(endx - half, starty + half);
             }
             closePath();
             state.getGraph().fill(currentPath);
             currentPath = null;

         case EN_NONE:
             // No rule is drawn
             break;
         default:
         } // end switch

         super.renderLeader(area);
     }

     /**
      * @see org.apache.fop.render.AbstractRenderer#renderImage(Image,
      * Rectangle2D)
      */
     public void renderImage(Image image, Rectangle2D pos) {
         // endTextObject();
         String url = image.getURL();
         drawImage(url, pos);
     }

     /**
      * @see org.apache.fop.render.AbstractPathOrientedRenderer#drawImage(
      *          java.lang.String, java.awt.geom.Rectangle2D, java.util.Map)
      */
     protected void drawImage(String url, Rectangle2D pos, Map 
foreignAttributes) {

         int x = currentIPPosition + (int)Math.round(pos.getX());
         int y = currentBPPosition + (int)Math.round(pos.getY());
         url = ImageFactory.getURL(url);

         ImageFactory fact = userAgent.getFactory().getImageFactory();
         FopImage fopimage = fact.getImage(url, userAgent);

         if (fopimage == null) {
             return;
         }
         if (!fopimage.load(FopImage.DIMENSIONS)) {
             return;
         }
         int w = fopimage.getWidth();
         int h = fopimage.getHeight();
         String mime = fopimage.getMimeType();
         if ("text/xml".equals(mime)) {
             if (!fopimage.load(FopImage.ORIGINAL_DATA)) {
                 return;
             }
             Document doc = ((XMLImage) fopimage).getDocument();
             String ns = ((XMLImage) fopimage).getNameSpace();
             renderDocument(doc, ns, pos, foreignAttributes);

         } else if ("image/svg+xml".equals(mime)) {
             if (!fopimage.load(FopImage.ORIGINAL_DATA)) {
                 return;
             }
             Document doc = ((XMLImage) fopimage).getDocument();
             String ns = ((XMLImage) fopimage).getNameSpace();

             renderDocument(doc, ns, pos, foreignAttributes);
         } else if ("image/eps".equals(mime)) {
             log.warn("EPS images are not supported by this renderer");
         } else {
             if (!fopimage.load(FopImage.BITMAP)) {
                 log.warn("Loading of bitmap failed: " + url);
                 return;
             }

             byte[] raw = fopimage.getBitmaps();

             // TODO Hardcoded color and sample models, FIX ME!
             ColorModel cm = new ComponentColorModel(
                     ColorSpace.getInstance(ColorSpace.CS_LINEAR_RGB),
                     new int[] {8, 8, 8},
                     false, false,
                     ColorModel.OPAQUE, DataBuffer.TYPE_BYTE);
             SampleModel sampleModel = new PixelInterleavedSampleModel(
                     DataBuffer.TYPE_BYTE, w, h, 3, w * 3, new int[] {0, 
1, 2});
             DataBuffer dbuf = new DataBufferByte(raw, w * h * 3);

             WritableRaster raster = 
Raster.createWritableRaster(sampleModel,
                     dbuf, null);

             java.awt.Image awtImage;
             // Combine the color model and raster into a buffered image
             awtImage = new BufferedImage(cm, raster, false, null);

             state.getGraph().drawImage(awtImage,
                     (int)(x / 1000f), (int)(y / 1000f),
                     (int)(pos.getWidth() / 1000f), 
(int)(pos.getHeight() / 1000f), null);
         }
     }

     /**
      * @see org.apache.fop.render.PrintRenderer#createRendererContext(
      *          int, int, int, int, java.util.Map)
      */
     protected RendererContext createRendererContext(int x, int y, int 
width, int height,
             Map foreignAttributes) {
         RendererContext context = super.createRendererContext(
                 x, y, width, height, foreignAttributes);
 
context.setProperty(Java2DRendererContextConstants.JAVA2D_STATE, state);
         return context;
     }

     /**
      * @see java.awt.print.Printable#print(java.awt.Graphics,
      * java.awt.print.PageFormat, int)
      */
     public int print(Graphics g, PageFormat pageFormat, int pageIndex)
             throws PrinterException {
         if (pageIndex >= getNumberOfPages()) {
             return NO_SUCH_PAGE;
         }

         if (state != null) {
             throw new IllegalStateException("state must be null");
         }
         Graphics2D graphics = (Graphics2D) g;
         try {
             PageViewport viewport = getPageViewport(pageIndex);
             AffineTransform at = graphics.getTransform();
             state = new Java2DGraphicsState(graphics, this.fontInfo, at);

             // reset the current Positions
             currentBPPosition = 0;
             currentIPPosition = 0;

             renderPageAreas(viewport.getPage());
             return PAGE_EXISTS;
         } catch (FOPException e) {
             log.error(e);
             return NO_SUCH_PAGE;
         } finally {
             state = null;
         }
     }

     /** @see 
org.apache.fop.render.AbstractPathOrientedRenderer#beginTextObject() */
     protected void beginTextObject() {
         //not necessary in Java2D
     }

     /** @see 
org.apache.fop.render.AbstractPathOrientedRenderer#endTextObject() */
     protected void endTextObject() {
         //not necessary in Java2D
     }

}


TIFFRenderer
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/*
  * Copyright 1999-2006 The Apache Software Foundation.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
  *
  *      http://www.apache.org/licenses/LICENSE-2.0
  *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */

/* $Id: TIFFRenderer.java 391332 2006-04-04 15:15:23Z jeremias $ */

package org.apache.fop.render.bitmap;

// Code originaly contributed by Oleg Tkachenko of Multiconn 
International Ltd
// (olegt@multiconn.com).

import java.awt.image.BufferedImage;
import java.awt.image.DataBuffer;
import java.awt.image.PixelInterleavedSampleModel;
import java.awt.image.RenderedImage;
import java.awt.image.SampleModel;
import java.awt.image.SinglePixelPackedSampleModel;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Iterator;

import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.configuration.ConfigurationException;
import org.apache.xmlgraphics.image.GraphicsUtil;
import org.apache.xmlgraphics.image.codec.tiff.TIFFEncodeParam;
import org.apache.xmlgraphics.image.codec.tiff.TIFFField;
import org.apache.xmlgraphics.image.codec.tiff.TIFFImageDecoder;
import org.apache.xmlgraphics.image.codec.tiff.TIFFImageEncoder;
import org.apache.xmlgraphics.image.rendered.FormatRed;
import org.apache.commons.logging.Log;
import org.apache.fop.apps.FOPException;
import org.apache.fop.apps.MimeConstants;
import org.apache.fop.render.java2d.Java2DRenderer;

/**
  * <p>
  * This class represents renderer to TIFF (Tagged Image File Format) 
format. It
  * is one of the most popular and flexible of the current public domain 
raster
  * file formats, which was is primarily designed for raster data 
interchange.
  * Supported compression types are:
  * <ul>
  * <li>Raw noncompressed data</li>
  * <li>Byte-oriented run-length encoding "PackBits" compression.</li>
  * <li>Modified Huffman Compression (CCITT Group 3 1D facsimile 
compression)</li>
  * <li>CCITT T.4 bilevel compression (CCITT Group 3 2D facsimile 
compression)</li>
  * <li>CCITT T.6 bilevel compression (CCITT Group 4 facsimile 
compression)</li>
  * <li>JPEG-in-TIFF compression</li>
  * <li>DEFLATE lossless compression (also known as "Zip-in-TIFF")</li>
  * <li>LZW compression</li>
  * TODO
  * <p>
  * This class actually does not render itself, instead it extends
  * <code>org.apache.fop.render.java2D.Java2DRenderer</code> and just encode
  * rendering results into TIFF format using Batik's image codec
  */
public class TIFFRenderer extends Java2DRenderer {

     /** The MIME type for tiff-Rendering */
     public static final String MIME_TYPE = MimeConstants.MIME_TIFF;

     /** */
     private TIFFEncodeParam renderParams;

     private OutputStream outputStream;

     /** @see org.apache.fop.render.AbstractRenderer */
     public String getMimeType() {
         return MIME_TYPE;
     }

     /** Creates TIFF renderer. */
     public TIFFRenderer() {
         renderParams = new TIFFEncodeParam();
         //Default to packbits compression which is widely supported
         renderParams.setCompression(TIFFEncodeParam.COMPRESSION_PACKBITS);
     }

     private int bufferedImageType= 0;
     /**
      * Configure the TIFF renderer. Get the configuration to be used for
      * compression
      * @see 
org.apache.avalon.framework.configuration.Configurable#configure(Configuration)
      */
     public void configure(Configuration cfg) throws 
ConfigurationException {

         //TODO Support output of monochrome bitmaps (fax-style)
         int comp = 
cfg.getChild("compression").getAttributeAsInteger("value", 1);
         String name = null;
         switch (comp) {
         case TIFFEncodeParam.COMPRESSION_NONE:
             name = "COMPRESSION_NONE";
             bufferedImageType= BufferedImage.TYPE_INT_ARGB;
             break;
         case TIFFEncodeParam.COMPRESSION_JPEG_TTN2:
             name = "COMPRESSION_JPEG_TTN2";
             bufferedImageType= BufferedImage.TYPE_INT_ARGB;
             break;
         case TIFFEncodeParam.COMPRESSION_PACKBITS:
             name = "COMPRESSION_PACKBITS";
             bufferedImageType= BufferedImage.TYPE_INT_ARGB;
             break;
         case TIFFEncodeParam.COMPRESSION_DEFLATE:
         	name = "COMPRESSION_DEFLATE";
         	bufferedImageType= BufferedImage.TYPE_INT_ARGB;
         	break;
         case TIFFEncodeParam.COMPRESSION_GROUP3_1D:
         	name = "COMPRESSION_GROUP3_1D";
         case TIFFEncodeParam.COMPRESSION_GROUP3_2D:
         	name = "COMPRESSION_GROUP3_2D";
         case TIFFEncodeParam.COMPRESSION_GROUP4:
             name = "COMPRESSION_GROUP4";
             bufferedImageType= BufferedImage.TYPE_BYTE_BINARY;
             break;
         default:
             log.info("TIFF compression not supported: " + comp);
             return;
         }
         log.info("TIFF compression set to " + name);

     }

     /** @see 
org.apache.fop.render.Renderer#startRenderer(java.io.OutputStream) */
     public void startRenderer(OutputStream outputStream) throws 
IOException {
         this.outputStream = outputStream;
         super.startRenderer(outputStream);
     }

     /** @see org.apache.fop.render.Renderer#stopRenderer() */
     public void stopRenderer() throws IOException {

         super.stopRenderer();
         log.debug("Starting Tiff encoding ...");

         //Set target resolution
         float pixSzMM = userAgent.getTargetPixelUnitToMillimeter();
         // num Pixs in 100 Meters
         int numPix = (int)(((1000 * 100) / pixSzMM) + 0.5);
         int denom = 100 * 100;  // Centimeters per 100 Meters;
         long [] rational = {numPix, denom};
         TIFFField [] fields = {
             new TIFFField(TIFFImageDecoder.TIFF_RESOLUTION_UNIT,
                           TIFFField.TIFF_SHORT, 1,
                           new char[] {(char)3}),
             new TIFFField(TIFFImageDecoder.TIFF_X_RESOLUTION,
                           TIFFField.TIFF_RATIONAL, 1,
                           new long[][] {rational}),
             new TIFFField(TIFFImageDecoder.TIFF_Y_RESOLUTION,
                           TIFFField.TIFF_RATIONAL, 1,
                           new long[][] {rational})
                 };
         renderParams.setExtraFields(fields);

         // Creates encoder
         TIFFImageEncoder enc = new TIFFImageEncoder(outputStream, 
renderParams);

         // Creates lazy iterator over generated page images
         Iterator pageImagesItr = new 
LazyPageImagesIterator(getNumberOfPages(), log);

         // The first image to be passed to enc
         RenderedImage first = (RenderedImage) pageImagesItr.next();

         // The other images are set to the renderParams
         renderParams.setExtraImages(pageImagesItr);

         // Start encoding
         enc.encode(first);

         // Cleaning
         outputStream.flush();
         clearViewportList();
         log.debug("Tiff encoding done.");

     }

     protected BufferedImage getBufferedImage(int bitmapWidth, int 
bitmapHeight)
     {
     	return new BufferedImage(
                 bitmapWidth, bitmapHeight, bufferedImageType);
     }

     /** Private inner class to lazy page rendering. */
     private class LazyPageImagesIterator implements Iterator {
         /** logging instance */
         private Log log;

         private int count;

         private int current = 0;

         /**
          * Main constructor
          * @param c number of pages to iterate over
          * @param log the logger to use (this is a hack so this 
compiles under JDK 1.3)
          */
         public LazyPageImagesIterator(int c, Log log) {
             count = c;
             this.log = log;
         }

         public boolean hasNext() {
             return current < count;
         }

         public Object next() {
             log.debug("[" + (current + 1) + "]");

             // Renders current page as image
             BufferedImage pageImage = null;
             try {
                 pageImage = getPageImage(current++);
             } catch (FOPException e) {
                 log.error(e);
                 return null;
             }

             switch (renderParams.getCompression()) {
             // These types of compression require a monochrome image
             /* these compression types are not supported by the Batik codec
             case TIFFEncodeParam.COMPRESSION_GROUP3_1D:
             case TIFFEncodeParam.COMPRESSION_GROUP3_2D:
             case TIFFEncodeParam.COMPRESSION_GROUP4:
                 BufferedImage faxImage = new BufferedImage(
                         pageImage.getWidth(), pageImage.getHeight(),
                         BufferedImage.TYPE_BYTE_BINARY);
                 faxImage.getGraphics().drawImage(pageImage, 0, 0, null);
                 return faxImage;*/
             default:
                 //Decorate the image with a packed sample model for 
encoding by the codec
                 SinglePixelPackedSampleModel sppsm;
                 sppsm = 
(SinglePixelPackedSampleModel)pageImage.getSampleModel();

                 int bands = sppsm.getNumBands();
                 int[] off = new int[bands];
                 int w = pageImage.getWidth();
                 int h = pageImage.getHeight();
                 for (int i = 0; i < bands; i++) {
                     off[i] = i;
                 }
                 SampleModel sm = new PixelInterleavedSampleModel(
                         DataBuffer.TYPE_BYTE, w, h, bands, w * bands, off);

                 RenderedImage rimg = new 
FormatRed(GraphicsUtil.wrap(pageImage), sm);
                 return rimg;
             }
         }

         public void remove() {
             throw new UnsupportedOperationException(
                     "Method 'remove' is not supported.");
         }
     }
}


---------------------------------------------------------------------
To unsubscribe, e-mail: fop-users-unsubscribe@xmlgraphics.apache.org
For additional commands, e-mail: fop-users-help@xmlgraphics.apache.org


Re: outputting TIFF-G images

Posted by Oliver Hernàndez Valls <oh...@notariado.org>.
Sorry if these questions are too obvious.


En/na Jeremias Maerki ha escrit:
> One more thing: The TIFFRenderer currently uses the internal codecs from
> XML Graphics Commons to encode TIFF images. 

I understand you are talking about 
org.apache.xmlgraphics.image.codec.tiff.TIFFImageEncoder in the method 
stopRenderer()

These do not support writing
> CCITT-G4 encoded images. We could switch to the ImageWriters I wrote for
> Batik and which are now available in XML Graphics Commons. They allow an
> abstraction from the underlying codec for image writing. There are
> implementations of the ImageWriter that write images through ImageIO

ImageIOTIFFImageWriter?

> which might have CCITT-capable codecs available but the code will have
> to be extended to choose the compression algorithm. 

So you're talking about subclassing ImageIOTIFFImageWriter (into batik 
or into fop?) or adding code into? to use, for example, TIFFFaxDecoder?

All in all, no easy
> solution to your requirement but certainly not much more than half a day
> of work.
> 
> On 10.09.2006 12:54:46 Jeremias Maerki wrote:
>> There's a configuration value you can set to modify the compression used
>> but it's poorly designed (requiring an integer value) and undocumented.
>> Furthermore, it does not support setting CCITT-G4 compression.
>> Generating monochrome (1bit) images has also not been implemented, yet.
>>
>> To implement all this, changes would have to be made in:
>> - Java2DRenderer.getPageImage(): Extract code into a protected method to
>> instantiate the BufferedImage that we paint on. Right now, it always
>> allocates an 24 bit RGB image with an 8-bit alpha channel.

OK

>> - TIFFRenderer.LazyPageImagesIterator.next(): Code to handle 1bit images.

Uncoment the code for TIFFEncodeParam.COMPRESSION_GROUP4? simply return 
the BufferedImage generated in the protected method above (I think is 
this one)? or some other hack?

>> - TIFFRenderer.configure(): provide better configuration using names for
>> compression methods.

What does this method does or have to do? I don't undertand why this 
method exists. It's reason is to log the compression?

>> - Override the new protected method described above to create the
>> Buffered image depending on the configuration.

OK

>>
>> If you don't want to hack FOP code, the work-around is to convert the
>> generated TIFF file after generation to CCITT format somehow. Obvious,
>> isn't it? :-)
>>
>> On 08.09.2006 11:04:22 Oliver Hernàndez Valls wrote:
>>> Hi all,
>>> 	I'm working with fop to generate MTIFF text images. At the moment i'm 
>>> using fop-trunk because no justification functionality is working in fop 
>>> 0.92 for tiffs.
>>> 	Right now I've all the functionality to generate parametrized text 
>>> images implemented. By default fop uses packbits compression and colored 
>>> image coding.
>>> 	I'd like to change the tiff coding to TIFF-G because generated images 
>>> with the default tiff coding are very big (around 9000 kB) and 
>>> coloration is not needed for the images I'm generating.
>>> 	I'm using the "new" FOUserAgent parameter setTargetResolution(int), but 
>>> I can't see any way to change the default encoding for tiff images.
>>> 	Some time ago I readed this somewhere in the source code: "//TODO 
>>> Support output of monochrome bitmaps (fax-style)", but don't know if it 
>>> has something to do with changing tiff coding.
>>>
>>> 	Any hint/workarround/documentation please?
>>>
>>> Thanks a lot, salut / cheers !
>>
>> Jeremias Maerki
> 
> 
> Jeremias Maerki
> 
> 
> ---------------------------------------------------------------------
> To unsubscribe, e-mail: fop-users-unsubscribe@xmlgraphics.apache.org
> For additional commands, e-mail: fop-users-help@xmlgraphics.apache.org
> 
> 

Thanks a lot!

---------------------------------------------------------------------
To unsubscribe, e-mail: fop-users-unsubscribe@xmlgraphics.apache.org
For additional commands, e-mail: fop-users-help@xmlgraphics.apache.org


Re: outputting TIFF-G images

Posted by Oliver Hernàndez Valls <oh...@notariado.org>.
Ok, yesterday I solved this problem by intalling jai tools. My error was 
that I installed jai lib, but this doesn't supply any new service 
provider, actually I don't know if this libs are really necessary.

Today I'll find a way to pass the page iterator to the tiff codec.

Salut!

En/na Oliver Hernàndez Valls ha escrit:
> I keep trying to make the TIFFRenderer work with CCITT T.6 bilevel 
> compression (CCITT Group 4 facsimile compression). But can't make it work.
> 
> When the outputStream flushes I have this exception:
> Caused by: java.util.NoSuchElementException
>     at javax.imageio.spi.FilterIterator.next(ServiceRegistry.java:808)
>     at javax.imageio.ImageIO$ImageWriterIterator.next(ImageIO.java:820)
>     at javax.imageio.ImageIO$ImageWriterIterator.next(ImageIO.java:805)
>     at 
> org.apache.xmlgraphics.image.writer.imageio.ImageIOImageWriter.writeImage(ImageIOImageWriter.java:73) 
> 
>     at 
> org.apache.fop.render.bitmap.TIFFRenderer.stopRenderer(TIFFRenderer.java:196) 
> 
>     at 
> org.apache.fop.area.RenderPagesModel.endDocument(RenderPagesModel.java:240)
>     at 
> org.apache.fop.area.AreaTreeHandler.endDocument(AreaTreeHandler.java:422)
>     at org.apache.fop.fo.FOTreeBuilder.endDocument(FOTreeBuilder.java:170)
>     at 
> org.apache.xml.serializer.ToXMLSAXHandler.endDocument(ToXMLSAXHandler.java:182) 
> 
>     at 
> org.apache.xalan.transformer.TransformerImpl.transformNode(TransformerImpl.java:1287) 
> 
>     ... 43 more
> 
>     I think the problem I have is that the IIORegistry has no service 
> providers for image/tiff mime types. And I don't know how to register 
> one. Neither I know where to find one.
>     Does somebody know how to make IIORegistry provide an encoder for 
> tiff images??
> 
> thanks a lot in advance!
> 
> this is the TIFFRenderer.java I have at present:
> /*
>  * Copyright 1999-2006 The Apache Software Foundation.
>  *
>  * Licensed under the Apache License, Version 2.0 (the "License");
>  * you may not use this file except in compliance with the License.
>  * You may obtain a copy of the License at
>  *
>  *      http://www.apache.org/licenses/LICENSE-2.0
>  *
>  * Unless required by applicable law or agreed to in writing, software
>  * distributed under the License is distributed on an "AS IS" BASIS,
>  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
>  * See the License for the specific language governing permissions and
>  * limitations under the License.
>  */
> 
> /* $Id: TIFFRenderer.java 391332 2006-04-04 15:15:23Z jeremias $ */
> 
> package org.apache.fop.render.bitmap;
> 
> // Code originaly contributed by Oleg Tkachenko of Multiconn 
> International Ltd
> // (olegt@multiconn.com).
> 
> import java.awt.image.BufferedImage;
> import java.awt.image.DataBuffer;
> import java.awt.image.PixelInterleavedSampleModel;
> import java.awt.image.RenderedImage;
> import java.awt.image.SampleModel;
> import java.awt.image.SinglePixelPackedSampleModel;
> import java.io.IOException;
> import java.io.OutputStream;
> import java.util.Iterator;
> 
> import org.apache.avalon.framework.configuration.Configuration;
> import org.apache.avalon.framework.configuration.ConfigurationException;
> import org.apache.commons.logging.Log;
> import org.apache.fop.apps.FOPException;
> import org.apache.fop.apps.MimeConstants;
> import org.apache.fop.render.java2d.Java2DRenderer;
> import org.apache.xmlgraphics.image.GraphicsUtil;
> import org.apache.xmlgraphics.image.codec.tiff.TIFFEncodeParam;
> import org.apache.xmlgraphics.image.rendered.FormatRed;
> import org.apache.xmlgraphics.image.writer.ImageWriter;
> import org.apache.xmlgraphics.image.writer.ImageWriterParams;
> import org.apache.xmlgraphics.image.writer.imageio.ImageIOTIFFImageWriter;
> 
> /**
>  * <p>
>  * This class represents renderer to TIFF (Tagged Image File Format) 
> format. It
>  * is one of the most popular and flexible of the current public domain 
> raster
>  * file formats, which was is primarily designed for raster data 
> interchange.
>  * Supported compression types are:
>  * <ul>
>  * <li>Raw noncompressed data</li>
>  * <li>Byte-oriented run-length encoding "PackBits" compression.</li>
>  * <li>Modified Huffman Compression (CCITT Group 3 1D facsimile 
> compression)</li>
>  * <li>CCITT T.4 bilevel compression (CCITT Group 3 2D facsimile 
> compression)</li>
>  * <li>CCITT T.6 bilevel compression (CCITT Group 4 facsimile 
> compression)</li>
>  * <li>JPEG-in-TIFF compression</li>
>  * <li>DEFLATE lossless compression (also known as "Zip-in-TIFF")</li>
>  * <li>LZW compression</li>
>  * TODO
>  * <p>
>  * This class actually does not render itself, instead it extends
>  * <code>org.apache.fop.render.java2D.Java2DRenderer</code> and just encode
>  * rendering results into TIFF format using Batik's image codec
>  */
> public class TIFFRenderer extends Java2DRenderer {
> 
>     /** The MIME type for tiff-Rendering */
>     public static final String MIME_TYPE = MimeConstants.MIME_TIFF;
> 
>     /** */
> //    private TIFFEncodeParam renderParams;
>     private ImageWriterParams iwParams= null;
> 
>     private OutputStream outputStream;
> 
>     /** @see org.apache.fop.render.AbstractRenderer */
>     public String getMimeType() {
>         return MIME_TYPE;
>     }
> 
>     /** Creates TIFF renderer. */
>     public TIFFRenderer() {
> //        renderParams = new TIFFEncodeParam();
>         //Default to packbits compression which is widely supported
> //        
> renderParams.setCompression(TIFFEncodeParam.COMPRESSION_PACKBITS);
>         iwParams= new ImageWriterParams();
>     }
> 
>     private int bufferedImageType= 0;
>     /**
>      * Configure the TIFF renderer. Get the configuration to be used for
>      * compression
>      * @see 
> org.apache.avalon.framework.configuration.Configurable#configure(Configuration) 
> 
>      */
>     public void configure(Configuration cfg) throws 
> ConfigurationException {
> 
>         String name = cfg.getChild("compression").getValue();
>         if(name.equalsIgnoreCase("COMPRESSION_NONE"))
>         {
> //            
> renderParams.setCompression(TIFFEncodeParam.COMPRESSION_NONE);
>             bufferedImageType= BufferedImage.TYPE_INT_ARGB;
>         }
>         else if ( name.equalsIgnoreCase("COMPRESSION_JPEG_TTN2") )
>         {
> //            
> renderParams.setCompression(TIFFEncodeParam.COMPRESSION_JPEG_TTN2);
>             bufferedImageType= BufferedImage.TYPE_INT_ARGB;
>         }
>         else if ( name.equalsIgnoreCase("COMPRESSION_PACKBITS") )
>         {
> //            
> renderParams.setCompression(TIFFEncodeParam.COMPRESSION_PACKBITS);
>             bufferedImageType= BufferedImage.TYPE_INT_ARGB;
>         }
>         else if ( name.equalsIgnoreCase("COMPRESSION_DEFLATE") )
>         {
> //            
> renderParams.setCompression(TIFFEncodeParam.COMPRESSION_DEFLATE);
>             bufferedImageType= BufferedImage.TYPE_INT_ARGB;
>         }
>         else if ( name.equalsIgnoreCase("COMPRESSION_GROUP3_1D") )
>         {
> //            
> renderParams.setCompression(TIFFEncodeParam.COMPRESSION_GROUP3_1D);
>             bufferedImageType= BufferedImage.TYPE_BYTE_BINARY;
>         }
>         else if (name.equalsIgnoreCase("COMPRESSION_GROUP3_2D") )
>         {
> //            
> renderParams.setCompression(TIFFEncodeParam.COMPRESSION_GROUP3_2D);
>             bufferedImageType= BufferedImage.TYPE_BYTE_BINARY;
>         }
>         else if (name.equalsIgnoreCase("COMPRESSION_GROUP4") )
>         {
> //            
> renderParams.setCompression(TIFFEncodeParam.COMPRESSION_GROUP4);
>             bufferedImageType= BufferedImage.TYPE_BYTE_BINARY;
>         }
>         else
>         {
>             log.info("TIFF compression not supported: " + name);
>             return;
>         }
>         iwParams.setCompressionMethod(name);
>         log.info("TIFF compression set to " + name);
>     }
> 
>     /** @see 
> org.apache.fop.render.Renderer#startRenderer(java.io.OutputStream) */
>     public void startRenderer(OutputStream outputStream) throws 
> IOException {
>         this.outputStream = outputStream;
>         super.startRenderer(outputStream);
>     }
> 
>     /** @see org.apache.fop.render.Renderer#stopRenderer() */
>     public void stopRenderer() throws IOException {
> 
>         super.stopRenderer();
>         log.debug("Starting Tiff encoding ...");
> 
> //        //Set target resolution
> //        float pixSzMM = userAgent.getTargetPixelUnitToMillimeter();
> //        // num Pixs in 100 Meters
> //        int numPix = (int)(((1000 * 100) / pixSzMM) + 0.5);
> //        int denom = 100 * 100;  // Centimeters per 100 Meters;
> //        long [] rational = {numPix, denom};
> //        TIFFField [] fields = {
> //            new TIFFField(TIFFImageDecoder.TIFF_RESOLUTION_UNIT,
> //                          TIFFField.TIFF_SHORT, 1,
> //                          new char[] {(char)3}),
> //            new TIFFField(TIFFImageDecoder.TIFF_X_RESOLUTION,
> //                          TIFFField.TIFF_RATIONAL, 1,
> //                          new long[][] {rational}),
> //            new TIFFField(TIFFImageDecoder.TIFF_Y_RESOLUTION,
> //                          TIFFField.TIFF_RATIONAL, 1,
> //                          new long[][] {rational})
> //                };
> //        renderParams.setExtraFields(fields);
> 
>         int dpi= Math.round(userAgent.getTargetResolution());
>         iwParams.setResolution(dpi);
>         // Creates encoder
> //        TIFFImageEncoder enc = new TIFFImageEncoder(outputStream, 
> renderParams);
>         ImageWriter iw= new ImageIOTIFFImageWriter();
> 
>         // Creates lazy iterator over generated page images
>         Iterator pageImagesItr = new 
> LazyPageImagesIterator(getNumberOfPages(), log);
> 
>         // The first image to be passed to enc
>         RenderedImage first = (RenderedImage) pageImagesItr.next();
> 
> //        // The other images are set to the renderParams
> //        renderParams.setExtraImages(pageImagesItr);
> 
>         // Start encoding
> //        enc.encode(first);
>         iw.writeImage(first, outputStream, iwParams);
> 
>         // Cleaning
>         outputStream.flush();
>         clearViewportList();
>         log.debug("Tiff encoding done.");
> 
>     }
> 
>     protected BufferedImage getBufferedImage(int bitmapWidth, int 
> bitmapHeight)
>     {
>         return new BufferedImage(
>                 bitmapWidth, bitmapHeight, bufferedImageType);
>     }
> 
>     /** Private inner class to lazy page rendering. */
>     private class LazyPageImagesIterator implements Iterator {
>         /** logging instance */
>         private Log log;
> 
>         private int count;
> 
>         private int current = 0;
> 
>         /**
>          * Main constructor
>          * @param c number of pages to iterate over
>          * @param log the logger to use (this is a hack so this compiles 
> under JDK 1.3)
>          */
>         public LazyPageImagesIterator(int c, Log log) {
>             count = c;
>             this.log = log;
>         }
> 
>         public boolean hasNext() {
>             return current < count;
>         }
> 
>         public Object next() {
>             log.debug("[" + (current + 1) + "]");
> 
>             // Renders current page as image
>             BufferedImage pageImage = null;
>             try {
>                 pageImage = getPageImage(current++);
>             } catch (FOPException e) {
>                 log.error(e);
>                 return null;
>             }
> 
> //            switch (renderParams.getCompression()) {
>             switch (TIFFEncodeParam.COMPRESSION_GROUP4) {
>             // These types of compression require a monochrome image
>             // these compression types are not supported by the Batik codec
>             case TIFFEncodeParam.COMPRESSION_GROUP3_1D:
>             case TIFFEncodeParam.COMPRESSION_GROUP3_2D:
>             case TIFFEncodeParam.COMPRESSION_GROUP4:
>                 BufferedImage faxImage = new BufferedImage(
>                         pageImage.getWidth(), pageImage.getHeight(),
>                         BufferedImage.TYPE_BYTE_BINARY);
>                 faxImage.getGraphics().drawImage(pageImage, 0, 0, null);
>                 return faxImage;
> //                  return pageImage;
>             default:
>                 //Decorate the image with a packed sample model for 
> encoding by the codec
>                 SinglePixelPackedSampleModel sppsm;
>                 sppsm = 
> (SinglePixelPackedSampleModel)pageImage.getSampleModel();
> 
>                 int bands = sppsm.getNumBands();
>                 int[] off = new int[bands];
>                 int w = pageImage.getWidth();
>                 int h = pageImage.getHeight();
>                 for (int i = 0; i < bands; i++) {
>                     off[i] = i;
>                 }
>                 SampleModel sm = new PixelInterleavedSampleModel(
>                         DataBuffer.TYPE_BYTE, w, h, bands, w * bands, off);
> 
>                 RenderedImage rimg = new 
> FormatRed(GraphicsUtil.wrap(pageImage), sm);
>                 return rimg;
>             }
>         }
> 
>         public void remove() {
>             throw new UnsupportedOperationException(
>                     "Method 'remove' is not supported.");
>         }
>     }
> }
> 
> 
> ---------------------------------------------------------------------
> To unsubscribe, e-mail: fop-users-unsubscribe@xmlgraphics.apache.org
> For additional commands, e-mail: fop-users-help@xmlgraphics.apache.org
> 
> 

---------------------------------------------------------------------
To unsubscribe, e-mail: fop-users-unsubscribe@xmlgraphics.apache.org
For additional commands, e-mail: fop-users-help@xmlgraphics.apache.org


Re: outputting TIFF-G images

Posted by Oliver Hernàndez Valls <oh...@notariado.org>.
I keep trying to make the TIFFRenderer work with CCITT T.6 bilevel 
compression (CCITT Group 4 facsimile compression). But can't make it work.

When the outputStream flushes I have this exception:
Caused by: java.util.NoSuchElementException
	at javax.imageio.spi.FilterIterator.next(ServiceRegistry.java:808)
	at javax.imageio.ImageIO$ImageWriterIterator.next(ImageIO.java:820)
	at javax.imageio.ImageIO$ImageWriterIterator.next(ImageIO.java:805)
	at 
org.apache.xmlgraphics.image.writer.imageio.ImageIOImageWriter.writeImage(ImageIOImageWriter.java:73)
	at 
org.apache.fop.render.bitmap.TIFFRenderer.stopRenderer(TIFFRenderer.java:196)
	at 
org.apache.fop.area.RenderPagesModel.endDocument(RenderPagesModel.java:240)
	at 
org.apache.fop.area.AreaTreeHandler.endDocument(AreaTreeHandler.java:422)
	at org.apache.fop.fo.FOTreeBuilder.endDocument(FOTreeBuilder.java:170)
	at 
org.apache.xml.serializer.ToXMLSAXHandler.endDocument(ToXMLSAXHandler.java:182)
	at 
org.apache.xalan.transformer.TransformerImpl.transformNode(TransformerImpl.java:1287)
	... 43 more

	I think the problem I have is that the IIORegistry has no service 
providers for image/tiff mime types. And I don't know how to register 
one. Neither I know where to find one.
	Does somebody know how to make IIORegistry provide an encoder for tiff 
images??

thanks a lot in advance!

this is the TIFFRenderer.java I have at present:
/*
  * Copyright 1999-2006 The Apache Software Foundation.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
  *
  *      http://www.apache.org/licenses/LICENSE-2.0
  *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */

/* $Id: TIFFRenderer.java 391332 2006-04-04 15:15:23Z jeremias $ */

package org.apache.fop.render.bitmap;

// Code originaly contributed by Oleg Tkachenko of Multiconn 
International Ltd
// (olegt@multiconn.com).

import java.awt.image.BufferedImage;
import java.awt.image.DataBuffer;
import java.awt.image.PixelInterleavedSampleModel;
import java.awt.image.RenderedImage;
import java.awt.image.SampleModel;
import java.awt.image.SinglePixelPackedSampleModel;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Iterator;

import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.configuration.ConfigurationException;
import org.apache.commons.logging.Log;
import org.apache.fop.apps.FOPException;
import org.apache.fop.apps.MimeConstants;
import org.apache.fop.render.java2d.Java2DRenderer;
import org.apache.xmlgraphics.image.GraphicsUtil;
import org.apache.xmlgraphics.image.codec.tiff.TIFFEncodeParam;
import org.apache.xmlgraphics.image.rendered.FormatRed;
import org.apache.xmlgraphics.image.writer.ImageWriter;
import org.apache.xmlgraphics.image.writer.ImageWriterParams;
import org.apache.xmlgraphics.image.writer.imageio.ImageIOTIFFImageWriter;

/**
  * <p>
  * This class represents renderer to TIFF (Tagged Image File Format) 
format. It
  * is one of the most popular and flexible of the current public domain 
raster
  * file formats, which was is primarily designed for raster data 
interchange.
  * Supported compression types are:
  * <ul>
  * <li>Raw noncompressed data</li>
  * <li>Byte-oriented run-length encoding "PackBits" compression.</li>
  * <li>Modified Huffman Compression (CCITT Group 3 1D facsimile 
compression)</li>
  * <li>CCITT T.4 bilevel compression (CCITT Group 3 2D facsimile 
compression)</li>
  * <li>CCITT T.6 bilevel compression (CCITT Group 4 facsimile 
compression)</li>
  * <li>JPEG-in-TIFF compression</li>
  * <li>DEFLATE lossless compression (also known as "Zip-in-TIFF")</li>
  * <li>LZW compression</li>
  * TODO
  * <p>
  * This class actually does not render itself, instead it extends
  * <code>org.apache.fop.render.java2D.Java2DRenderer</code> and just encode
  * rendering results into TIFF format using Batik's image codec
  */
public class TIFFRenderer extends Java2DRenderer {

     /** The MIME type for tiff-Rendering */
     public static final String MIME_TYPE = MimeConstants.MIME_TIFF;

     /** */
//    private TIFFEncodeParam renderParams;
     private ImageWriterParams iwParams= null;

     private OutputStream outputStream;

     /** @see org.apache.fop.render.AbstractRenderer */
     public String getMimeType() {
         return MIME_TYPE;
     }

     /** Creates TIFF renderer. */
     public TIFFRenderer() {
//        renderParams = new TIFFEncodeParam();
         //Default to packbits compression which is widely supported
//        renderParams.setCompression(TIFFEncodeParam.COMPRESSION_PACKBITS);
         iwParams= new ImageWriterParams();
     }

     private int bufferedImageType= 0;
     /**
      * Configure the TIFF renderer. Get the configuration to be used for
      * compression
      * @see 
org.apache.avalon.framework.configuration.Configurable#configure(Configuration)
      */
     public void configure(Configuration cfg) throws 
ConfigurationException {

     	String name = cfg.getChild("compression").getValue();
     	if(name.equalsIgnoreCase("COMPRESSION_NONE"))
     	{
//    		renderParams.setCompression(TIFFEncodeParam.COMPRESSION_NONE);
             bufferedImageType= BufferedImage.TYPE_INT_ARGB;
     	}
     	else if ( name.equalsIgnoreCase("COMPRESSION_JPEG_TTN2") )
     	{
//    		renderParams.setCompression(TIFFEncodeParam.COMPRESSION_JPEG_TTN2);
     		bufferedImageType= BufferedImage.TYPE_INT_ARGB;
     	}
     	else if ( name.equalsIgnoreCase("COMPRESSION_PACKBITS") )
     	{
//    		renderParams.setCompression(TIFFEncodeParam.COMPRESSION_PACKBITS);
     		bufferedImageType= BufferedImage.TYPE_INT_ARGB;
     	}
     	else if ( name.equalsIgnoreCase("COMPRESSION_DEFLATE") )
     	{
//    		renderParams.setCompression(TIFFEncodeParam.COMPRESSION_DEFLATE);
     		bufferedImageType= BufferedImage.TYPE_INT_ARGB;
     	}
     	else if ( name.equalsIgnoreCase("COMPRESSION_GROUP3_1D") )
     	{
//    		renderParams.setCompression(TIFFEncodeParam.COMPRESSION_GROUP3_1D);
     		bufferedImageType= BufferedImage.TYPE_BYTE_BINARY;
     	}
     	else if (name.equalsIgnoreCase("COMPRESSION_GROUP3_2D") )
     	{
//    		renderParams.setCompression(TIFFEncodeParam.COMPRESSION_GROUP3_2D);
     		bufferedImageType= BufferedImage.TYPE_BYTE_BINARY;
     	}
     	else if (name.equalsIgnoreCase("COMPRESSION_GROUP4") )
     	{
//    		renderParams.setCompression(TIFFEncodeParam.COMPRESSION_GROUP4);
     		bufferedImageType= BufferedImage.TYPE_BYTE_BINARY;
     	}
     	else
     	{
             log.info("TIFF compression not supported: " + name);
             return;
         }
     	iwParams.setCompressionMethod(name);
         log.info("TIFF compression set to " + name);
     }

     /** @see 
org.apache.fop.render.Renderer#startRenderer(java.io.OutputStream) */
     public void startRenderer(OutputStream outputStream) throws 
IOException {
         this.outputStream = outputStream;
         super.startRenderer(outputStream);
     }

     /** @see org.apache.fop.render.Renderer#stopRenderer() */
     public void stopRenderer() throws IOException {

         super.stopRenderer();
         log.debug("Starting Tiff encoding ...");

//        //Set target resolution
//        float pixSzMM = userAgent.getTargetPixelUnitToMillimeter();
//        // num Pixs in 100 Meters
//        int numPix = (int)(((1000 * 100) / pixSzMM) + 0.5);
//        int denom = 100 * 100;  // Centimeters per 100 Meters;
//        long [] rational = {numPix, denom};
//        TIFFField [] fields = {
//            new TIFFField(TIFFImageDecoder.TIFF_RESOLUTION_UNIT,
//                          TIFFField.TIFF_SHORT, 1,
//                          new char[] {(char)3}),
//            new TIFFField(TIFFImageDecoder.TIFF_X_RESOLUTION,
//                          TIFFField.TIFF_RATIONAL, 1,
//                          new long[][] {rational}),
//            new TIFFField(TIFFImageDecoder.TIFF_Y_RESOLUTION,
//                          TIFFField.TIFF_RATIONAL, 1,
//                          new long[][] {rational})
//                };
//        renderParams.setExtraFields(fields);

         int dpi= Math.round(userAgent.getTargetResolution());
         iwParams.setResolution(dpi);
         // Creates encoder
//        TIFFImageEncoder enc = new TIFFImageEncoder(outputStream, 
renderParams);
         ImageWriter iw= new ImageIOTIFFImageWriter();

         // Creates lazy iterator over generated page images
         Iterator pageImagesItr = new 
LazyPageImagesIterator(getNumberOfPages(), log);

         // The first image to be passed to enc
         RenderedImage first = (RenderedImage) pageImagesItr.next();

//        // The other images are set to the renderParams
//        renderParams.setExtraImages(pageImagesItr);

         // Start encoding
//        enc.encode(first);
         iw.writeImage(first, outputStream, iwParams);

         // Cleaning
         outputStream.flush();
         clearViewportList();
         log.debug("Tiff encoding done.");

     }

     protected BufferedImage getBufferedImage(int bitmapWidth, int 
bitmapHeight)
     {
     	return new BufferedImage(
                 bitmapWidth, bitmapHeight, bufferedImageType);
     }

     /** Private inner class to lazy page rendering. */
     private class LazyPageImagesIterator implements Iterator {
         /** logging instance */
         private Log log;

         private int count;

         private int current = 0;

         /**
          * Main constructor
          * @param c number of pages to iterate over
          * @param log the logger to use (this is a hack so this 
compiles under JDK 1.3)
          */
         public LazyPageImagesIterator(int c, Log log) {
             count = c;
             this.log = log;
         }

         public boolean hasNext() {
             return current < count;
         }

         public Object next() {
             log.debug("[" + (current + 1) + "]");

             // Renders current page as image
             BufferedImage pageImage = null;
             try {
                 pageImage = getPageImage(current++);
             } catch (FOPException e) {
                 log.error(e);
                 return null;
             }

//            switch (renderParams.getCompression()) {
             switch (TIFFEncodeParam.COMPRESSION_GROUP4) {
             // These types of compression require a monochrome image
             // these compression types are not supported by the Batik codec
             case TIFFEncodeParam.COMPRESSION_GROUP3_1D:
             case TIFFEncodeParam.COMPRESSION_GROUP3_2D:
             case TIFFEncodeParam.COMPRESSION_GROUP4:
                 BufferedImage faxImage = new BufferedImage(
                         pageImage.getWidth(), pageImage.getHeight(),
                         BufferedImage.TYPE_BYTE_BINARY);
                 faxImage.getGraphics().drawImage(pageImage, 0, 0, null);
                 return faxImage;
//            	  return pageImage;
             default:
                 //Decorate the image with a packed sample model for 
encoding by the codec
                 SinglePixelPackedSampleModel sppsm;
                 sppsm = 
(SinglePixelPackedSampleModel)pageImage.getSampleModel();

                 int bands = sppsm.getNumBands();
                 int[] off = new int[bands];
                 int w = pageImage.getWidth();
                 int h = pageImage.getHeight();
                 for (int i = 0; i < bands; i++) {
                     off[i] = i;
                 }
                 SampleModel sm = new PixelInterleavedSampleModel(
                         DataBuffer.TYPE_BYTE, w, h, bands, w * bands, off);

                 RenderedImage rimg = new 
FormatRed(GraphicsUtil.wrap(pageImage), sm);
                 return rimg;
             }
         }

         public void remove() {
             throw new UnsupportedOperationException(
                     "Method 'remove' is not supported.");
         }
     }
}


---------------------------------------------------------------------
To unsubscribe, e-mail: fop-users-unsubscribe@xmlgraphics.apache.org
For additional commands, e-mail: fop-users-help@xmlgraphics.apache.org


Re: outputting TIFF-G images

Posted by Jeremias Maerki <de...@jeremias-maerki.ch>.
One more thing: The TIFFRenderer currently uses the internal codecs from
XML Graphics Commons to encode TIFF images. These do not support writing
CCITT-G4 encoded images. We could switch to the ImageWriters I wrote for
Batik and which are now available in XML Graphics Commons. They allow an
abstraction from the underlying codec for image writing. There are
implementations of the ImageWriter that write images through ImageIO
which might have CCITT-capable codecs available but the code will have
to be extended to choose the compression algorithm. All in all, no easy
solution to your requirement but certainly not much more than half a day
of work.

On 10.09.2006 12:54:46 Jeremias Maerki wrote:
> There's a configuration value you can set to modify the compression used
> but it's poorly designed (requiring an integer value) and undocumented.
> Furthermore, it does not support setting CCITT-G4 compression.
> Generating monochrome (1bit) images has also not been implemented, yet.
> 
> To implement all this, changes would have to be made in:
> - Java2DRenderer.getPageImage(): Extract code into a protected method to
> instantiate the BufferedImage that we paint on. Right now, it always
> allocates an 24 bit RGB image with an 8-bit alpha channel.
> - TIFFRenderer.LazyPageImagesIterator.next(): Code to handle 1bit images.
> - TIFFRenderer.configure(): provide better configuration using names for
> compression methods.
> - Override the new protected method described above to create the
> Buffered image depending on the configuration.
> 
> If you don't want to hack FOP code, the work-around is to convert the
> generated TIFF file after generation to CCITT format somehow. Obvious,
> isn't it? :-)
> 
> On 08.09.2006 11:04:22 Oliver Hernàndez Valls wrote:
> > Hi all,
> > 	I'm working with fop to generate MTIFF text images. At the moment i'm 
> > using fop-trunk because no justification functionality is working in fop 
> > 0.92 for tiffs.
> > 	Right now I've all the functionality to generate parametrized text 
> > images implemented. By default fop uses packbits compression and colored 
> > image coding.
> > 	I'd like to change the tiff coding to TIFF-G because generated images 
> > with the default tiff coding are very big (around 9000 kB) and 
> > coloration is not needed for the images I'm generating.
> > 	I'm using the "new" FOUserAgent parameter setTargetResolution(int), but 
> > I can't see any way to change the default encoding for tiff images.
> > 	Some time ago I readed this somewhere in the source code: "//TODO 
> > Support output of monochrome bitmaps (fax-style)", but don't know if it 
> > has something to do with changing tiff coding.
> > 
> > 	Any hint/workarround/documentation please?
> > 
> > Thanks a lot, salut / cheers !
> 
> 
> Jeremias Maerki


Jeremias Maerki


---------------------------------------------------------------------
To unsubscribe, e-mail: fop-users-unsubscribe@xmlgraphics.apache.org
For additional commands, e-mail: fop-users-help@xmlgraphics.apache.org


Re: outputting TIFF-G images

Posted by Jeremias Maerki <de...@jeremias-maerki.ch>.
There's a configuration value you can set to modify the compression used
but it's poorly designed (requiring an integer value) and undocumented.
Furthermore, it does not support setting CCITT-G4 compression.
Generating monochrome (1bit) images has also not been implemented, yet.

To implement all this, changes would have to be made in:
- Java2DRenderer.getPageImage(): Extract code into a protected method to
instantiate the BufferedImage that we paint on. Right now, it always
allocates an 24 bit RGB image with an 8-bit alpha channel.
- TIFFRenderer.LazyPageImagesIterator.next(): Code to handle 1bit images.
- TIFFRenderer.configure(): provide better configuration using names for
compression methods.
- Override the new protected method described above to create the
Buffered image depending on the configuration.

If you don't want to hack FOP code, the work-around is to convert the
generated TIFF file after generation to CCITT format somehow. Obvious,
isn't it? :-)

On 08.09.2006 11:04:22 Oliver Hernàndez Valls wrote:
> Hi all,
> 	I'm working with fop to generate MTIFF text images. At the moment i'm 
> using fop-trunk because no justification functionality is working in fop 
> 0.92 for tiffs.
> 	Right now I've all the functionality to generate parametrized text 
> images implemented. By default fop uses packbits compression and colored 
> image coding.
> 	I'd like to change the tiff coding to TIFF-G because generated images 
> with the default tiff coding are very big (around 9000 kB) and 
> coloration is not needed for the images I'm generating.
> 	I'm using the "new" FOUserAgent parameter setTargetResolution(int), but 
> I can't see any way to change the default encoding for tiff images.
> 	Some time ago I readed this somewhere in the source code: "//TODO 
> Support output of monochrome bitmaps (fax-style)", but don't know if it 
> has something to do with changing tiff coding.
> 
> 	Any hint/workarround/documentation please?
> 
> Thanks a lot, salut / cheers !


Jeremias Maerki


---------------------------------------------------------------------
To unsubscribe, e-mail: fop-users-unsubscribe@xmlgraphics.apache.org
For additional commands, e-mail: fop-users-help@xmlgraphics.apache.org