com.lowagie.text.Image Java Examples

The following examples show how to use com.lowagie.text.Image. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PdfJndiReport.java    From javamelody with Apache License 2.0 6 votes vote down vote up
private void writeJndiBinding(JndiBinding jndiBinding) throws BadElementException, IOException {
	final PdfPCell defaultCell = getDefaultCell();
	defaultCell.setHorizontalAlignment(Element.ALIGN_LEFT);
	final String name = jndiBinding.getName();
	final String className = jndiBinding.getClassName();
	final String contextPath = jndiBinding.getContextPath();
	final String value = jndiBinding.getValue();
	if (contextPath != null) {
		final Image image = getFolderImage();
		final Phrase phrase = new Phrase("", cellFont);
		phrase.add(new Chunk(image, 0, 0));
		phrase.add(new Chunk(" " + name));
		addCell(phrase);
	} else {
		addCell(name);
	}
	addCell(className != null ? className : "");
	addCell(value != null ? value : "");
}
 
Example #2
Source File: AbsolutePositionsTest.java    From itext2 with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Adds an Image at an absolute position.
 */
@Test
public void main() throws Exception {

	// step 1: creation of a document-object
	Document document = new Document();

	// step 2:
	// we create a writer that listens to the document
	// and directs a PDF-stream to a file

	PdfWriter.getInstance(document, PdfTestBase.getOutputStream("absolutepositions.pdf"));

	// step 3: we open the document
	document.open();

	// step 4: we add content
	Image png = Image.getInstance(PdfTestBase.RESOURCES_DIR + "hitchcock.png");
	png.setAbsolutePosition(171, 250);
	document.add(png);
	png.setAbsolutePosition(342, 500);
	document.add(png);

	// step 5: we close the document
	document.close();
}
 
Example #3
Source File: PdfPCell.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Constructs a deep copy of a <CODE>PdfPCell</CODE>.
 * 
 * @param cell the <CODE>PdfPCell</CODE> to duplicate
 */
public PdfPCell(PdfPCell cell) {
    super(cell.llx, cell.lly, cell.urx, cell.ury);
    cloneNonPositionParameters(cell);
    verticalAlignment = cell.verticalAlignment;
    paddingLeft = cell.paddingLeft;
    paddingRight = cell.paddingRight;
    paddingTop = cell.paddingTop;
    paddingBottom = cell.paddingBottom;
    phrase = cell.phrase;
    fixedHeight = cell.fixedHeight;
    minimumHeight = cell.minimumHeight;
    noWrap = cell.noWrap;
    colspan = cell.colspan;
    rowspan = cell.rowspan;
    if (cell.table != null)
        table = new PdfPTable(cell.table);
    image = Image.getInstance(cell.image);
    cellEvent = cell.cellEvent;
    useDescender = cell.useDescender;
    column = ColumnText.duplicate(cell.column);
    useBorderPadding = cell.useBorderPadding;
    rotation = cell.rotation;
}
 
Example #4
Source File: PdfPCell.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Constructs a <CODE>PdfPCell</CODE> with an <CODE>Image</CODE>.
 * The default padding is 0.25 for a border width of 0.5.
 * 
 * @param image the <CODE>Image</CODE>
 * @param fit <CODE>true</CODE> to fit the image to the cell
 */
public PdfPCell(Image image, boolean fit) {
    super(0, 0, 0, 0);
    borderWidth = 0.5f;
    border = BOX;
    if (fit) {
        this.image = image;
        column.setLeading(0, 1);
        setPadding(borderWidth / 2);
    }
    else {
        column.addText(this.phrase = new Phrase(new Chunk(image, 0, 0)));
        column.setLeading(0, 1);
        setPadding(0);
    }
}
 
Example #5
Source File: AlignmentTest.java    From itext2 with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Demonstrates the alignment method.
 */
@Test
public void main() throws Exception {
	// step 1: creation of a document-object
	Document document = new Document();
	// step 2: creation of a writer
	PdfWriter.getInstance(document, PdfTestBase.getOutputStream("alignment.pdf"));

	// step 3: we open the document
	document.open();

	Image gif = Image.getInstance(PdfTestBase.RESOURCES_DIR + "vonnegut.gif");
	gif.setAlignment(Image.RIGHT);
	Image jpeg = Image.getInstance(PdfTestBase.RESOURCES_DIR + "otsoe.jpg");
	jpeg.setAlignment(Image.MIDDLE);
	Image png = Image.getInstance(PdfTestBase.RESOURCES_DIR + "hitchcock.png");
	png.setAlignment(Image.LEFT);

	document.add(gif);
	document.add(jpeg);
	document.add(png);

	// step 5: we close the document
	document.close();
}
 
Example #6
Source File: TransactionSummaryController.java    From primefaces-blueprints with The Unlicense 6 votes vote down vote up
public void preProcessPDF(Object document) throws IOException,
		BadElementException, DocumentException {
	Document pdf = (Document) document;
	pdf.setPageSize(PageSize.A4);
	pdf.open();

	ServletContext servletContext = (ServletContext) FacesContext
			.getCurrentInstance().getExternalContext().getContext();
	String logo = servletContext.getRealPath("") + File.separator
			+ "resources" + File.separator + "images" + File.separator
			+ "logo" + File.separator + "logo.png";
	Image image = Image.getInstance(logo);
	image.scaleAbsolute(100f, 50f);
	pdf.add(image);
	// add a couple of blank lines
	pdf.add(Chunk.NEWLINE);
	pdf.add(Chunk.NEWLINE);
	Font fontbold = FontFactory.getFont("Times-Roman", 16, Font.BOLD);
	fontbold.setColor(55, 55, 55);
	;
	pdf.add(new Paragraph("Transaction Summary", fontbold));
	// add a couple of blank lines
	pdf.add(Chunk.NEWLINE);
	pdf.add(Chunk.NEWLINE);
}
 
Example #7
Source File: InvestmentSummaryController.java    From primefaces-blueprints with The Unlicense 6 votes vote down vote up
public void preProcessPDF(Object document) throws IOException, BadElementException, DocumentException {  
    Document pdf = (Document) document; 
    pdf.setPageSize(PageSize.A3); 
    pdf.open();  
     
    ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();  
    String logo = servletContext.getRealPath("") + File.separator +"resources" + File.separator + "images" + File.separator +"logo" + File.separator + "logo.png";  
    Image image=Image.getInstance(logo);
    image.scaleAbsolute(100f, 50f);
    pdf.add(image); 
    // add a couple of blank lines
       pdf.add( Chunk.NEWLINE );
       pdf.add( Chunk.NEWLINE );
    Font fontbold = FontFactory.getFont("Times-Roman", 16, Font.BOLD);
    fontbold.setColor(55, 55, 55);;
    pdf.add(new Paragraph("Investment Summary",fontbold));
    // add a couple of blank lines
    pdf.add( Chunk.NEWLINE );
    pdf.add( Chunk.NEWLINE );
}
 
Example #8
Source File: BmpImage.java    From itext2 with GNU Lesser General Public License v3.0 5 votes vote down vote up
/** Reads a BMP from an url.
 * @param url the url
 * @throws IOException on error
 * @return the image
 */    
public static Image getImage(URL url) throws IOException {
    InputStream is = null;
    try {
        is = url.openStream();
        Image img = getImage(is);
        img.setUrl(url);
        return img;
    }
    finally {
        if (is != null) {
            is.close();
        }
    }
}
 
Example #9
Source File: PdfDocumentFactory.java    From javamelody with Apache License 2.0 5 votes vote down vote up
Image getSmallImage(String resourceFileName) throws DocumentException, IOException {
	Image image = smallImagesByResourceName.get(resourceFileName);
	if (image == null) {
		image = getImage(resourceFileName);
		image.scaleAbsolute(8, 8);
		smallImagesByResourceName.put(resourceFileName, image);
	}
	return image;
}
 
Example #10
Source File: PdfCreator.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
boolean isToCutWidth(Image img, int tableWidth) {
	int imgWidth = (int) img.getWidth();
	if (imgWidth > (4 * tableWidth))
		return true;
	else
		return false;
}
 
Example #11
Source File: PdfStamperImp.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
void setThumbnail(Image image, int page) throws PdfException, DocumentException {
	PdfIndirectReference thumb = getImageReference(addDirectImageSimple(image));
	reader.resetReleasePage();
	PdfDictionary dic = reader.getPageN(page);
	dic.put(PdfName.THUMB, thumb);
	reader.resetReleasePage();
}
 
Example #12
Source File: BmpImage.java    From itext2 with GNU Lesser General Public License v3.0 5 votes vote down vote up
private Image indexedModel(byte bdata[], int bpc, int paletteEntries) throws BadElementException {
    Image img = new ImgRaw(width, height, 1, bpc, bdata);
    PdfArray colorspace = new PdfArray();
    colorspace.add(PdfName.INDEXED);
    colorspace.add(PdfName.DEVICERGB);
    byte np[] = getPalette(paletteEntries);
    int len = np.length;
    colorspace.add(new PdfNumber(len / 3 - 1));
    colorspace.add(new PdfString(np));
    PdfDictionary ad = new PdfDictionary();
    ad.put(PdfName.COLORSPACE, colorspace);
    img.setAdditional(ad);
    return img;
}
 
Example #13
Source File: BarcodePDF417.java    From itext2 with GNU Lesser General Public License v3.0 5 votes vote down vote up
/** Creates a <CODE>java.awt.Image</CODE>.
 * @param foreground the color of the bars
 * @param background the color of the background
 * @return the image
 */    
public java.awt.Image createAwtImage(Color foreground, Color background) {
    int f = foreground.getRGB();
    int g = background.getRGB();
    Canvas canvas = new Canvas();

    paintCode();
    int h = (int)yHeight;
    int pix[] = new int[bitColumns * codeRows * h];
    int stride = (bitColumns + 7) / 8;
    int ptr = 0;
    for (int k = 0; k < codeRows; ++k) {
        int p = k * stride;
        for (int j = 0; j < bitColumns; ++j) {
            int b = outBits[p + (j / 8)] & 0xff;
            b <<= j % 8;
            pix[ptr++] = (b & 0x80) == 0 ? g : f;
        }
        for (int j = 1; j < h; ++j) {
            System.arraycopy(pix, ptr - bitColumns, pix, ptr + bitColumns * (j - 1), bitColumns);
        }
        ptr += bitColumns * (h - 1);
    }
    
    java.awt.Image img = canvas.createImage(new MemoryImageSource(bitColumns, codeRows * h, pix, 0, bitColumns));
    return img;
}
 
Example #14
Source File: SAXiTextHandler.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
protected void addImage(Image img) throws EmptyStackException {
	// if there is an element on the stack...
	Object current = stack.pop();
	// ...and it's a Chapter or a Section, the Image can be
	// added directly
	if (current instanceof Chapter || current instanceof Section || current instanceof Cell) {
		((TextElementArray) current).add(img);
		stack.push(current);
		return;
	}
	// ...if not, we need to to a lot of stuff
	else {
		Stack newStack = new Stack();
		while (!(current instanceof Chapter || current instanceof Section || current instanceof Cell)) {
			newStack.push(current);
			if (current instanceof Anchor) {
				img.setAnnotation(new Annotation(0, 0, 0, 0, ((Anchor) current).getReference()));
			}
			current = stack.pop();
		}
		((TextElementArray) current).add(img);
		stack.push(current);
		while (!newStack.empty()) {
			stack.push(newStack.pop());
		}
		return;
	}
}
 
Example #15
Source File: BarcodePDF417.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Creates a <CODE>java.awt.Image</CODE>.
 * 
 * @param foreground the color of the bars
 * @param background the color of the background
 * @return the image
 */
public java.awt.Image createAwtImage(Color foreground, Color background) {
	int f = foreground.getRGB();
	int g = background.getRGB();
	Canvas canvas = new Canvas();

	paintCode();
	int h = (int) yHeight;
	int pix[] = new int[bitColumns * codeRows * h];
	int stride = (bitColumns + 7) / 8;
	int ptr = 0;
	for (int k = 0; k < codeRows; ++k) {
		int p = k * stride;
		for (int j = 0; j < bitColumns; ++j) {
			int b = outBits[p + j / 8] & 0xff;
			b <<= j % 8;
			pix[ptr++] = (b & 0x80) == 0 ? g : f;
		}
		for (int j = 1; j < h; ++j) {
			System.arraycopy(pix, ptr - bitColumns, pix, ptr + bitColumns * (j - 1), bitColumns);
		}
		ptr += bitColumns * (h - 1);
	}

	java.awt.Image img = canvas.createImage(new MemoryImageSource(bitColumns, codeRows * h, pix, 0, bitColumns));
	return img;
}
 
Example #16
Source File: JBIG2Image.java    From itext2 with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * returns an Image representing the given page.
 * @param ra	the file or array containing the image
 * @param page	the page number of the image
 * @return	an Image object
 */
public static Image getJbig2Image(RandomAccessFileOrArray ra, int page) {
	if (page < 1)
           throw new IllegalArgumentException("The page number must be >= 1.");
	
	try {
		JBIG2SegmentReader sr = new JBIG2SegmentReader(ra);
		sr.read();
		JBIG2SegmentReader.JBIG2Page p = sr.getPage(page);
		Image img = new ImgJBIG2(p.pageBitmapWidth, p.pageBitmapHeight, p.getData(true), sr.getGlobal(true));
		return img;
	} catch (Exception e) {
        throw new ExceptionConverter(e);
    }
}
 
Example #17
Source File: PngImage.java    From MesquiteCore with GNU Lesser General Public License v3.0 5 votes vote down vote up
/** Reads a PNG from an url.
 * @param url the url
 * @throws IOException on error
 * @return the image
 */    
public static Image getImage(URL url) throws IOException {
    InputStream is = null;
    try {
        is = url.openStream();
        Image img = getImage(is);
        img.setUrl(url);
        return img;
    }
    finally {
        if (is != null) {
            is.close();
        }
    }
}
 
Example #18
Source File: PdfContentByte.java    From MesquiteCore with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Adds an <CODE>Image</CODE> to the page. The <CODE>Image</CODE> must have
 * absolute positioning.
 * @param image the <CODE>Image</CODE> object
 * @throws DocumentException if the <CODE>Image</CODE> does not have absolute positioning
 */
public void addImage(Image image) throws DocumentException {
    if (!image.hasAbsolutePosition())
        throw new DocumentException("The image must have absolute positioning.");
    float matrix[] = image.matrix();
    matrix[Image.CX] = image.absoluteX() - matrix[Image.CX];
    matrix[Image.CY] = image.absoluteY() - matrix[Image.CY];
    addImage(image, matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5]);
}
 
Example #19
Source File: PdfCell.java    From itext2 with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Returns the height needed to draw the remaining text.
 *
 * @return a height
 */

public float remainingHeight() {
    float result = 0f;
    for (Iterator i = images.iterator(); i.hasNext();) {
        Image image = (Image) i.next();
        result += image.getScaledHeight();
    }
    return remainingLinesHeight() + cellspacing + 2 * cellpadding + result;
}
 
Example #20
Source File: BarcodeDatamatrix.java    From itext2 with GNU Lesser General Public License v3.0 5 votes vote down vote up
/** Gets an <CODE>Image</CODE> with the barcode. A successful call to the method <CODE>generate()</CODE>
 * before calling this method is required.
 * @return the barcode <CODE>Image</CODE>
 * @throws BadElementException on error
 */    
public Image createImage() throws BadElementException {
    if (image == null)
        return null;
    byte g4[] = CCITTG4Encoder.compress(image, width + 2 * ws, height + 2 * ws);
    return Image.getInstance(width + 2 * ws, height + 2 * ws, false, Image.CCITTG4, 0, g4, null);
}
 
Example #21
Source File: Coversheet.java    From kfs with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * @see org.kuali.kfs.module.tem.pdf.PdfStream#print(java.io.OutputStream)
 * @throws Exception
 */
@Override
public void print(final OutputStream stream) throws Exception {
    final Font titleFont  = FontFactory.getFont(FontFactory.HELVETICA, 20, Font.BOLD);
    final Font headerFont = FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD);
    final Font normalFont = FontFactory.getFont(FontFactory.HELVETICA, 12, Font.NORMAL);

    final Document doc = new Document();
    final PdfWriter writer = PdfWriter.getInstance(doc, stream);
    doc.open();
    if(getDocumentNumber()!=null){
        Image image=Image.getInstance(new BarcodeHelper().generateBarcodeImage(getDocumentNumber()),null);
        doc.add(image);
    }

    final Paragraph title = new Paragraph("TEM Coversheet", titleFont);
    doc.add(title);

    final Paragraph faxNumber = new Paragraph("Fax this page to " + SpringContext.getBean(ParameterService.class).getParameterValueAsString(TravelReimbursementDocument.class, FAX_NUMBER), normalFont);
    doc.add(faxNumber);

    final Paragraph header = new Paragraph("", headerFont);
    header.setAlignment(ALIGN_RIGHT);
    header.add("Document Number: " + getDocumentNumber());
    doc.add(header);
    doc.add(getInstructionsParagraph());
    doc.add(getMailtoParagraph());
    doc.add(Chunk.NEWLINE);
    doc.add(getTripInfo());
    doc.add(Chunk.NEWLINE);
    doc.add(getPersonalInfo());
    doc.add(Chunk.NEWLINE);
    doc.add(getExpenses());

    drawAlignmentMarks(writer.getDirectContent());

    doc.close();
    writer.close();
}
 
Example #22
Source File: PdfCell.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Adds an image to this Cell.
 *
 * @param i the image to add
 * @param left the left border
 * @param right the right border
 * @param extraHeight extra height to add above image
 * @param alignment horizontal alignment (constant from Element class)
 * @return the height of the image
 */

private float addImage(Image i, float left, float right, float extraHeight, int alignment) {
	Image image = Image.getInstance(i);
	if (image.getScaledWidth() > right - left) {
		image.scaleToFit(right - left, Float.MAX_VALUE);
	}
	flushCurrentLine();
	if (line == null) {
		line = new PdfLine(left, right, alignment, leading);
	}
	PdfLine imageLine = line;

	// left and right in chunk is relative to the start of the line
	right = right - left;
	left = 0f;

	if ((image.getAlignment() & Image.RIGHT) == Image.RIGHT) {
		left = right - image.getScaledWidth();
	} else if ((image.getAlignment() & Image.MIDDLE) == Image.MIDDLE) {
		left = left + (right - left - image.getScaledWidth()) / 2f;
	}
	Chunk imageChunk = new Chunk(image, left, 0);
	imageLine.add(new PdfChunk(imageChunk, null));
	addLine(imageLine);
	return imageLine.height();
}
 
Example #23
Source File: BmpImage.java    From itext2 with GNU Lesser General Public License v3.0 5 votes vote down vote up
/** Reads a BMP from a stream. The stream is not closed.
 * The BMP may not have a header and be considered as a plain DIB.
 * @param is the stream
 * @param noHeader true to process a plain DIB
 * @param size the size of the DIB. Not used for a BMP
 * @throws IOException on error
 * @return the image
 */    
public static Image getImage(InputStream is, boolean noHeader, int size) throws IOException {
    BmpImage bmp = new BmpImage(is, noHeader, size);
    try {
        Image img = bmp.getImage();
        img.setDpi((int)(bmp.xPelsPerMeter * 0.0254d + 0.5d), (int)(bmp.yPelsPerMeter * 0.0254d + 0.5d));
        img.setOriginalType(Image.ORIGINAL_BMP);
        return img;
    }
    catch (BadElementException be) {
        throw new ExceptionConverter(be);
    }
}
 
Example #24
Source File: ImageAreaLayout.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
protected void initialize( ) throws BirtException
{
	// choose the layout manager
	reader = new ImageReader( content, context.getSupportedImageFormats( ) );
	int result = reader.read( );
	switch ( result )
	{
		case ImageReader.RESOURCE_UNREACHABLE:
			// display the alt text or prompt object not accessible.
			layout = createAltTextLayout( ImageReader.RESOURCE_UNREACHABLE );
			break;
		case ImageReader.UNSUPPORTED_OBJECTS:
			// display the alt text or prompt unsupported objects.
			layout = createAltTextLayout( ImageReader.UNSUPPORTED_OBJECTS );
			break;
		case ImageReader.OBJECT_LOADED_SUCCESSFULLY:
			//the object is accessible.
			if ( reader.getType( ) == ImageReader.TYPE_IMAGE_OBJECT
					|| reader.getType( ) == ImageReader.TYPE_CONVERTED_SVG_OBJECT )
			{
				try
				{
					imageObject = Image.getInstance( reader.getByteArray( ) );
				}
				catch ( Exception e )
				{
					logger.log( Level.WARNING, e.getLocalizedMessage( ) );
				}
				// unrecognized image formats.
				if ( imageObject == null )
				{
					layout = createAltTextLayout( ImageReader.UNSUPPORTED_OBJECTS );
					break;
				}
			}
			layout = new ConcreteImageLayout( context, parent, content,
					reader.getByteArray( ) );
			break;
	}
}
 
Example #25
Source File: PdfCell.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Returns the height needed to draw the remaining text.
 *
 * @return a height
 */

public float remainingHeight() {
	float result = 0f;
	for (Iterator i = images.iterator(); i.hasNext();) {
		Image image = (Image) i.next();
		result += image.getScaledHeight();
	}
	return remainingLinesHeight() + cellspacing + 2 * cellpadding + result;
}
 
Example #26
Source File: BmpImage.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Reads a BMP from an url.
 * 
 * @param url the url
 * @throws IOException on error
 * @return the image
 */
public static Image getImage(URL url) throws IOException {
	InputStream is = null;
	try {
		is = url.openStream();
		Image img = getImage(is);
		img.setUrl(url);
		return img;
	} finally {
		if (is != null) {
			is.close();
		}
	}
}
 
Example #27
Source File: BmpImage.java    From itext2 with GNU Lesser General Public License v3.0 5 votes vote down vote up
/** Reads a BMP from a byte array.
 * @param data the byte array
 * @throws IOException on error
 * @return the image
 */    
public static Image getImage(byte data[]) throws IOException {
    ByteArrayInputStream is = new ByteArrayInputStream(data);
    Image img = getImage(is);
    img.setOriginalData(data);
    return img;
}
 
Example #28
Source File: Barcode.java    From itext2 with GNU Lesser General Public License v3.0 5 votes vote down vote up
/** Creates an <CODE>Image</CODE> with the barcode.
 * @param cb the <CODE>PdfContentByte</CODE> to create the <CODE>Image</CODE>. It
 * serves no other use
 * @param barColor the color of the bars. It can be <CODE>null</CODE>
 * @param textColor the color of the text. It can be <CODE>null</CODE>
 * @return the <CODE>Image</CODE>
 * @see #placeBarcode(PdfContentByte cb, Color barColor, Color textColor)
 */    
public Image createImageWithBarcode(PdfContentByte cb, Color barColor, Color textColor) {
    try {
        return Image.getInstance(createTemplateWithBarcode(cb, barColor, textColor));
    }
    catch (Exception e) {
        throw new ExceptionConverter(e);
    }
}
 
Example #29
Source File: PngImage.java    From itext2 with GNU Lesser General Public License v3.0 5 votes vote down vote up
/** Reads a PNG from an url.
 * @param url the url
 * @throws IOException on error
 * @return the image
 */    
public static Image getImage(URL url) throws IOException {
    InputStream is = null;
    try {
        is = url.openStream();
        Image img = getImage(is);
        img.setUrl(url);
        return img;
    }
    finally {
        if (is != null) {
            is.close();
        }
    }
}
 
Example #30
Source File: BmpImage.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
private Image read8Bit(int paletteEntries) throws IOException, BadElementException {
	byte bdata[] = new byte[width * height];
	// Padding bytes at the end of each scanline
	int padding = 0;

	// width * bitsPerPixel should be divisible by 32
	int bitsPerScanline = width * 8;
	if (bitsPerScanline % 32 != 0) {
		padding = (bitsPerScanline / 32 + 1) * 32 - bitsPerScanline;
		padding = (int) Math.ceil(padding / 8.0);
	}

	int imSize = (width + padding) * height;

	// Read till we have the whole image
	byte values[] = new byte[imSize];
	int bytesRead = 0;
	while (bytesRead < imSize) {
		bytesRead += inputStream.read(values, bytesRead, imSize - bytesRead);
	}

	if (isBottomUp) {

		// Convert the bottom up image to a top down format by copying
		// one scanline from the bottom to the top at a time.
		for (int i = 0; i < height; i++) {
			System.arraycopy(values, imSize - (i + 1) * (width + padding), bdata, i * width, width);
		}
	} else {
		for (int i = 0; i < height; i++) {
			System.arraycopy(values, i * (width + padding), bdata, i * width, width);
		}
	}
	return indexedModel(bdata, 8, paletteEntries);
}