List of usage examples for java.awt.geom AffineTransform getScaleInstance
public static AffineTransform getScaleInstance(double sx, double sy)
From source file:org.squidy.designer.util.ImageUtils.java
/** * @param source/* ww w. j av a2s. c o m*/ * @param width * @param height * @return * @throws IOException */ public static BufferedImage scale(BufferedImage source, int width, int height) throws IOException { BufferedImage target = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Graphics2D g = target.createGraphics(); AffineTransform at = AffineTransform.getScaleInstance((double) width / source.getWidth(), (double) height / source.getHeight()); g.drawRenderedImage(source, at); return target; }
From source file:org.squidy.nodes.ScreenDispatcher.java
/** * @param image// w ww . ja v a 2 s. c om * @param width * @param height * @return */ private BufferedImage scaleImageTo(BufferedImage image, int width, int height) { int imageWidth = image.getWidth(null); int imageHeight = image.getHeight(null); double scaleX = (double) width / imageWidth; double scaleY = (double) height / imageHeight; if (flipScreen) { scaleX = (double) width / imageHeight; scaleY = (double) height / imageWidth; } AffineTransform at = AffineTransform.getScaleInstance(scaleX, scaleY); if (flipScreen) { at.rotate(Math.PI / 2); at.translate(0, -imageHeight); } BufferedImage scaledImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D g2d = scaledImage.createGraphics(); g2d.drawImage(image, at, null); g2d.dispose(); return scaledImage; }
From source file:org.viafirma.util.QRCodeUtil.java
/** * Genera un justificante de firma de un fichero pdf de entrada. * //from w w w . j a va 2 s .co m * @param input * Fichero pdf de entrada * @param texto * @param textoQR * @param codFirma * @param out * @throws ExcepcionErrorInterno */ public void firmarPDF(InputStream input, String texto, String texto2Line, String textoQR, String codFirma, OutputStream out) throws ExcepcionErrorInterno { // leemos el pdf utilizando iText. try { // Recuperamos el documento original PdfReader reader = new PdfReader(input); // Obtenemos el tamao de la pgina Rectangle pageSize = reader.getPageSize(1); // Creamos un nuevo documento del mismo tamao que el original Document document = new Document(pageSize); // creo una instancia para escritura en el documento PdfWriter writer = PdfWriter.getInstance(document, out); document.open(); // insertamos la portada del documento que estamos firmando. float escala = (pageSize.getHeight() - 350) / pageSize.getHeight(); // Aadimos al documento la imagen de cabecera y de pie addContent(texto, texto2Line, textoQR, codFirma, document, pageSize, true, false); PdfContentByte cb = writer.getDirectContent(); PdfImportedPage portada = writer.getImportedPage(reader, 1); cb.setRGBColorStroke(0xCC, 0xCC, 0xCC); cb.transform(AffineTransform.getTranslateInstance(document.leftMargin(), 210)); cb.transform(AffineTransform.getScaleInstance(escala, escala)); cb.addTemplate(portada, 0, 0);// , escala, 0, 0, escala,dx,dy); document.close(); out.close(); } catch (Exception e) { throw new ExcepcionErrorInterno(CodigoError.ERROR_INTERNO, e); } }
From source file:org.viafirma.util.QRCodeUtil.java
/** * Genera un documento sellado en fichero pdf. * /*from www.j a v a 2 s.c om*/ * @param input * Fichero pdf de entrada * @param texto * @param textoQR * @param codFirma * @param out * @throws ExcepcionErrorInterno */ public void firmarPDFSellado(InputStream input, String texto, String texto2Line, String textoQR, String codFirma, OutputStream out) throws ExcepcionErrorInterno { // leemos el pdf utilizando iText. try { // Recuperamos el documento original PdfReader reader = new PdfReader(input); // Obtenemos el tamao de la pgina Rectangle pageSize = reader.getPageSize(1); // Creamos un nuevo documento del mismo tamao que el original Document document = new Document(pageSize); // creo una instancia para escritura en el documento PdfWriter writer = PdfWriter.getInstance(document, out); document.open(); // Aadimos al documento la imagen de cabecera y de pie float altoCabeceraYPie = addContent(texto, texto2Line, textoQR, codFirma, document, pageSize, true, true); altoCabeceraYPie = altoCabeceraYPie + document.topMargin(); // insertamos la portada del documento que estamos firmando. float escala = (pageSize.getHeight() - altoCabeceraYPie) / pageSize.getHeight(); PdfContentByte cb = writer.getDirectContent(); PdfImportedPage portada = writer.getImportedPage(reader, 1); cb.setRGBColorStroke(0xCC, 0xCC, 0xCC); cb.transform(AffineTransform.getScaleInstance(escala, escala)); cb.transform(AffineTransform.getTranslateInstance(document.leftMargin() * 2.5, ALTO_ETIQUETA + document.topMargin())); cb.addTemplate(portada, 0, 0);// , escala, 0, 0, escala,dx,dy); document.close(); out.close(); } catch (Exception e) { throw new ExcepcionErrorInterno(CodigoError.ERROR_INTERNO, e); } }
From source file:org.zkoss.poi.ss.util.SheetUtil.java
/** * Compute width of a single cell/*from w ww .j a v a 2s.c o m*/ * * @param cell the cell whose width is to be calculated * @param defaultCharWidth the width of a single character * @param formatter formatter used to prepare the text to be measured * @param useMergedCells whether to use merged cells * @return the width in pixels */ public static double getCellWidth(Cell cell, int defaultCharWidth, DataFormatter formatter, boolean useMergedCells) { Sheet sheet = cell.getSheet(); Workbook wb = sheet.getWorkbook(); Row row = cell.getRow(); int column = cell.getColumnIndex(); int colspan = 1; for (int i = 0; i < sheet.getNumMergedRegions(); i++) { CellRangeAddress region = sheet.getMergedRegion(i); if (containsCell(region, row.getRowNum(), column)) { if (!useMergedCells) { // If we're not using merged cells, skip this one and move on to the next. return -1; } cell = row.getCell(region.getFirstColumn()); colspan = 1 + region.getLastColumn() - region.getFirstColumn(); } } CellStyle style = cell.getCellStyle(); int cellType = cell.getCellType(); // for formula cells we compute the cell width for the cached formula result if (cellType == Cell.CELL_TYPE_FORMULA) cellType = cell.getCachedFormulaResultType(); Font font = wb.getFontAt(style.getFontIndex()); AttributedString str; TextLayout layout; double width = -1; if (cellType == Cell.CELL_TYPE_STRING) { RichTextString rt = cell.getRichStringCellValue(); String[] lines = rt.getString().split("\\n"); for (int i = 0; i < lines.length; i++) { String txt = lines[i] + defaultChar; str = new AttributedString(txt); copyAttributes(font, str, 0, txt.length()); if (rt.numFormattingRuns() > 0) { // TODO: support rich text fragments } layout = new TextLayout(str.getIterator(), fontRenderContext); if (style.getRotation() != 0) { /* * Transform the text using a scale so that it's height is increased by a multiple of the leading, * and then rotate the text before computing the bounds. The scale results in some whitespace around * the unrotated top and bottom of the text that normally wouldn't be present if unscaled, but * is added by the standard Excel autosize. */ AffineTransform trans = new AffineTransform(); trans.concatenate( AffineTransform.getRotateInstance(style.getRotation() * 2.0 * Math.PI / 360.0)); trans.concatenate(AffineTransform.getScaleInstance(1, fontHeightMultiple)); width = Math.max(width, ((layout.getOutline(trans).getBounds().getWidth() / colspan) / defaultCharWidth) + cell.getCellStyle().getIndention()); } else { width = Math.max(width, ((layout.getBounds().getWidth() / colspan) / defaultCharWidth) + cell.getCellStyle().getIndention()); } } } else { String sval = null; if (cellType == Cell.CELL_TYPE_NUMERIC) { // Try to get it formatted to look the same as excel try { sval = formatter.formatCellValue(cell, dummyEvaluator); } catch (Exception e) { sval = String.valueOf(cell.getNumericCellValue()); } } else if (cellType == Cell.CELL_TYPE_BOOLEAN) { sval = String.valueOf(cell.getBooleanCellValue()).toUpperCase(); } if (sval != null) { String txt = sval + defaultChar; str = new AttributedString(txt); copyAttributes(font, str, 0, txt.length()); layout = new TextLayout(str.getIterator(), fontRenderContext); if (style.getRotation() != 0) { /* * Transform the text using a scale so that it's height is increased by a multiple of the leading, * and then rotate the text before computing the bounds. The scale results in some whitespace around * the unrotated top and bottom of the text that normally wouldn't be present if unscaled, but * is added by the standard Excel autosize. */ AffineTransform trans = new AffineTransform(); trans.concatenate( AffineTransform.getRotateInstance(style.getRotation() * 2.0 * Math.PI / 360.0)); trans.concatenate(AffineTransform.getScaleInstance(1, fontHeightMultiple)); width = Math.max(width, ((layout.getOutline(trans).getBounds().getWidth() / colspan) / defaultCharWidth) + cell.getCellStyle().getIndention()); } else { width = Math.max(width, ((layout.getBounds().getWidth() / colspan) / defaultCharWidth) + cell.getCellStyle().getIndention()); } } } return width; }
From source file:paintbasico2d.VentanaPrincipal.java
private void jButtonAgrandarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAgrandarActionPerformed // TODO add your handling code here: VentanaInterna vi = (VentanaInterna) (escritorio.getSelectedFrame()); if (vi != null) { BufferedImage ImgSource = vi.getLienzo().getImage(); if (ImgSource != null) { AffineTransform at = AffineTransform.getScaleInstance(1.25, 1.25); try { AffineTransformOp atop = new AffineTransformOp(at, AffineTransformOp.TYPE_BILINEAR); BufferedImage imgdest = atop.filter(ImgSource, null); vi.getLienzo().setImage(imgdest); vi.getLienzo().repaint(); } catch (Exception e) { System.err.println("error"); }// ww w. j ava 2s.c o m } } }
From source file:paintbasico2d.VentanaPrincipal.java
private void jButtonAchicarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAchicarActionPerformed VentanaInterna vi = (VentanaInterna) (escritorio.getSelectedFrame()); if (vi != null) { BufferedImage ImgSource = vi.getLienzo().getImage(); if (ImgSource != null) { AffineTransform at = AffineTransform.getScaleInstance(0.75, 0.75); try { AffineTransformOp atop = new AffineTransformOp(at, AffineTransformOp.TYPE_BILINEAR); BufferedImage imgdest = atop.filter(ImgSource, null); vi.getLienzo().setImage(imgdest); vi.getLienzo().repaint(); } catch (Exception e) { System.err.println("error"); }//from w ww . j ava2s . c o m } } // TODO add your handling code here: }
From source file:ro.finsiel.eunis.admin.EUNISUploadServlet.java
/** * This method is used to upload pictures for species/sites within database. * * @param fileItems/*from w w w . j a v a2 s . co m*/ * FileItems which came form request parsed by the upload method (DiskFileUpload).<br /> * Contains information about upload (HTTP FORM headers, parsed as elements). * @throws Exception * Is throwed for various reasons: IOException, database down etc. */ private void uploadPicture(List fileItems) throws Exception { natureObjectInfo = new NatureObjectInfo(); String filename = ""; String idObject = ""; String description = ""; String natureObjectType = ""; String source = ""; String sourceUrl = ""; String license = ""; boolean mainPicture = false; FileItem uploadedFileItem = null; for (int i = 0; i < fileItems.size(); i++) { FileItem item = (FileItem) fileItems.get(i); if (item.isFormField()) { // FORM FIELD String fieldName = item.getFieldName(); String fieldValue = item.getString(); // Filename if (null != fieldName && fieldName.equalsIgnoreCase("filename")) { filename = fieldValue; } // Id object if (null != fieldName && fieldName.equalsIgnoreCase("idobject")) { idObject = fieldValue; } // Description if (null != fieldName && fieldName.equalsIgnoreCase("description")) { description = new String(fieldValue.getBytes("iso-8859-1"), "UTF-8"); } // Nature object type if (null != fieldName && fieldName.equalsIgnoreCase("natureobjecttype")) { natureObjectType = fieldValue; } // Main picture if (null != fieldName && fieldName.equalsIgnoreCase("main_picture")) { mainPicture = true; } // Source if (null != fieldName && fieldName.equalsIgnoreCase("source")) { source = new String(fieldValue.getBytes("iso-8859-1"), "UTF-8"); } // Source URL if (null != fieldName && fieldName.equalsIgnoreCase("sourceUrl")) { sourceUrl = new String(fieldValue.getBytes("iso-8859-1"), "UTF-8"); } // License if (null != fieldName && fieldName.equalsIgnoreCase("license")) { license = new String(fieldValue.getBytes("iso-8859-1"), "UTF-8"); } } else { // / UPLOAD FIELD filename = item.getName(); uploadedFileItem = item; } } String uploadDir = ""; if (natureObjectType.equalsIgnoreCase("Species")) { uploadDir = getServletConfig().getServletContext().getInitParameter("UPLOAD_DIR_PICTURES_SPECIES"); } else if (natureObjectType.equalsIgnoreCase("Sites")) { uploadDir = getServletConfig().getServletContext().getInitParameter("UPLOAD_DIR_PICTURES_SITES"); } else if (natureObjectType.equalsIgnoreCase("Habitats")) { uploadDir = getServletConfig().getServletContext().getInitParameter("UPLOAD_DIR_PICTURES_HABITATS"); } // Save the file in the right dir... filename = FileUtils.getRealName(filename); String imgName = filename; String suffix = imgName.substring(imgName.lastIndexOf(".")); if (suffix == null || suffix.equals("") || (!suffix.equalsIgnoreCase(".jpg") && !suffix.equalsIgnoreCase(".jpeg") && !suffix.equalsIgnoreCase(".gif") && !suffix.equalsIgnoreCase(".png") && !suffix.equalsIgnoreCase(".tif") && !suffix.equalsIgnoreCase(".tiff"))) { throw new Exception( "File has to be in one of the following formats: jpg, jpeg, gif, png, tif, tiff (case-insensitive)"); } String fname = UniqueID.getUniqueID() + suffix.toLowerCase(); filename = BASE_DIR + uploadDir + fname; // System.out.println("filename = " + filename); File file = new File(filename); // System.out.println("file = " + file); uploadedFileItem.write(file); natureObjectInfo.filename = fname; natureObjectInfo.description = description; natureObjectInfo.idObject = idObject; natureObjectInfo.natureObjectType = natureObjectType; // Sync the database with the pictures String scientificName = null; if (natureObjectType.equalsIgnoreCase("Species")) { scientificName = PicturesHelper.findSpeciesByIDObject(idObject); } else if (natureObjectType.equalsIgnoreCase("Sites")) { scientificName = PicturesHelper.findSitesByIDObject(idObject); } else if (natureObjectType.equalsIgnoreCase("Habitats")) { scientificName = PicturesHelper.findHabitatsByIDObject(idObject); } Chm62edtNatureObjectPicturePersist pictureObject = new Chm62edtNatureObjectPicturePersist(); pictureObject.setDescription(description); pictureObject.setMainPicture(false); pictureObject.setFileName(fname); pictureObject.setIdObject(idObject); pictureObject.setName(scientificName); pictureObject.setNatureObjectType(natureObjectType); pictureObject.setSource(source); pictureObject.setSourceUrl(sourceUrl); pictureObject.setLicense(license); new Chm62edtNatureObjectPictureDomain().save(pictureObject); String mainPictureFilename = idObject + "_main_picture" + suffix; Chm62edtNatureObjectPictureDomain domain = new Chm62edtNatureObjectPictureDomain(); List<Chm62edtNatureObjectPicturePersist> mainPictures = domain.findWhere( " FILE_NAME = '" + mainPictureFilename + "' and MAIN_PIC = 1 and NAME = '" + scientificName + "'"); if (mainPictures == null || mainPictures.size() == 0) { mainPicture = true; } // processing main picture if (mainPicture) { BufferedImage image = ImageIO.read(file); double ratio = (double) image.getWidth() / (double) image.getHeight(); double idealRatio = (double) MAX_WIDTH / (double) MAX_HEIGHT; int newHeight = 0, newWidth = 0; if (ratio > idealRatio) { newWidth = Math.min(image.getWidth(), MAX_WIDTH); newHeight = (int) (newWidth / ratio); } else { newHeight = Math.min(image.getHeight(), MAX_HEIGHT); newWidth = (int) (newHeight * ratio); } AffineTransform at = AffineTransform.getScaleInstance((double) newWidth / (double) image.getWidth(), (double) newHeight / (double) image.getHeight()); BufferedImage output = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB); ((Graphics2D) output.getGraphics()).drawRenderedImage(image, at); File outputFile = new File(BASE_DIR + uploadDir + mainPictureFilename); ImageIO.write(output, "JPG", outputFile); Chm62edtNatureObjectPicturePersist mainPicturePersist = new Chm62edtNatureObjectPicturePersist(); // delete old mainPictures for (Chm62edtNatureObjectPicturePersist mainPic : mainPictures) { domain.save(mainPic); domain.delete(mainPic); } // create new one mainPicturePersist.setDescription(description); mainPicturePersist.setMainPicture(true); mainPicturePersist.setFileName(mainPictureFilename); mainPicturePersist.setIdObject(idObject); mainPicturePersist.setName(scientificName); mainPicturePersist.setNatureObjectType(natureObjectType); mainPicturePersist.setMaxWidth(new Integer(newWidth)); mainPicturePersist.setMaxHeight(new Integer(newHeight)); mainPicturePersist.setSource(source); mainPicturePersist.setSourceUrl(sourceUrl); mainPicturePersist.setLicense(license); domain.save(mainPicturePersist); } }
From source file:se.trixon.almond.GraphicsHelper.java
public static BufferedImage flipBufferedImageX(BufferedImage bufferedImage) { AffineTransform affineTransform = AffineTransform.getScaleInstance(-1, 1); affineTransform.translate(-bufferedImage.getWidth(null), 0); AffineTransformOp affineTransformOp = new AffineTransformOp(affineTransform, AffineTransformOp.TYPE_NEAREST_NEIGHBOR); return affineTransformOp.filter(bufferedImage, null); }
From source file:se.trixon.almond.GraphicsHelper.java
public static BufferedImage flipBufferedImageY(BufferedImage bufferedImage) { AffineTransform affineTransform = AffineTransform.getScaleInstance(1, -1); affineTransform.translate(-bufferedImage.getWidth(null), 0); AffineTransformOp affineTransformOp = new AffineTransformOp(affineTransform, AffineTransformOp.TYPE_NEAREST_NEIGHBOR); return affineTransformOp.filter(bufferedImage, null); }