/** constructor */ public DanceQueuePanel() { // flow layout setLayout(new FlowLayout()); // uses buffer to draw arrows based on queues in an array myImage = new BufferedImage(600, 600, BufferedImage.TYPE_INT_RGB); myBuffer = myImage.getGraphics(); // uses timer to queue buffer changes time = 0; timer = new Timer(5, new Listener()); timer.start(); setFocusable(true); // picks instructions based on song & level if (Danceoff.getSong() == -1 && Danceoff.getDifficulty() == 0) { arrows = new Arrow[] {new UpArrow(1000), new DownArrow(2000), new LeftArrow(3000)}; } // setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.BLACK, 3), // "DanceQueuePanel")); // load images for arrows rightArrowImg = null; leftArrowImg = null; upArrowImg = null; downArrowImg = null; try { rightArrowImg = ImageIO.read(new File("arrowB right.png")); leftArrowImg = ImageIO.read(new File("arrowB left.png")); upArrowImg = ImageIO.read(new File("arrowB up copy.png")); downArrowImg = ImageIO.read(new File("arrowB down.png")); } catch (IOException e) { warn("YOU FAIL", e); System.exit(2); } }
/** * Testing TIFF capabilities. * * @throws IOException If an error occured while writting the image. */ @Test public void testTIFFWrite() throws IOException { assertTrue("Assertions should be enabled.", ImageWorker.class.desiredAssertionStatus()); // Get the image of the world with transparency. final ImageWorker worker = new ImageWorker(worldImage); show(worker, "Input file"); // ///////////////////////////////////////////////////////////////////// // tiff deflated untiled // ///////////////////////////////////////////////////////////////////// final File outFile = TestData.temp(this, "temp.tiff"); worker.writeTIFF(outFile, "Deflate", 0.75f, -1, -1); final ImageWorker readWorker = new ImageWorker(ImageIO.read(outFile)); show(readWorker, "Tiff untiled"); // ///////////////////////////////////////////////////////////////////// // tiff deflated compressed tiled // ///////////////////////////////////////////////////////////////////// worker.setImage(worldImage); worker.writeTIFF(outFile, "Deflate", 0.75f, 32, 32); readWorker.setImage(ImageIO.read(outFile)); show(readWorker, "Tiff jpeg compressed, tiled"); outFile.delete(); }
/** * Convert a source to a BufferedImage. Source supported: * File,BufferedImage,InputStream,URL,ImageInputStream, byte[] * * @param imageType the ImageType to use * @param source source to generate BufferedImage from * @return Enhanced BufferedImage * @throws NullPointerException _ * @throws IOException _ * @throws UnsupportedOperationException throws this is the source is of unsupported type */ public static <T> BufferedImage convertImageType(final ImageType imageType, final T source) throws NullPointerException, IOException, UnsupportedOperationException { if (verifyNotNull(imageType, source)) { BufferedImage target = null; if (source instanceof File) { target = convert(ImageIO.read((File) source), imageType); } else if (source instanceof BufferedImage) { target = convert((BufferedImage) source, imageType); } else if (source instanceof InputStream) { target = convert(ImageIO.read((InputStream) source), imageType); } else if (source instanceof URL) { target = convert(ImageIO.read((URL) source), imageType); } else if (source instanceof ImageInputStream) { target = convert(ImageIO.read((ImageInputStream) source), imageType); } else if (source instanceof byte[]) { final InputStream streamOfInput = new ByteArrayInputStream((byte[]) source); target = convert(ImageIO.read(streamOfInput), imageType); } else { throw new UnsupportedOperationException("%s is not supported. Read JavaDoc."); } if (verifyNotNull(target)) { LOGGER.info( String.format( "Returning requested converted object<%s> as target", target.getClass().getName())); return target; } throw new NullPointerException("Return value was null."); } throw new NullPointerException("Nilled param detected. Please verify your params!"); }
/** * Salva BufferedImage no arquivo informado na prop<br> * * <p><b>Exemplo:><br> * <code>salvarImagem(img)</code> * * @param img BufferedImage a ser salva * @author roberto */ private void salvarImagem(BufferedImage img) { ImageWriter writer = null; Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName(formatoImagem); if (iter.hasNext()) { writer = (ImageWriter) iter.next(); } ImageOutputStream ios; try { ios = ImageIO.createImageOutputStream(new File(prop.getProp("dirImg"))); writer.setOutput(ios); ImageWriteParam param = new JPEGImageWriteParam(java.util.Locale.getDefault()); param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); param.setCompressionQuality(1); writer.write(null, new IIOImage(img, null, null), param); } catch (IOException e) { e.printStackTrace(); } }
public static void main(String[] args) { try { System.loadLibrary(Core.NATIVE_LIBRARY_NAME); File input = new File("traffic_signal.jpg"); BufferedImage image = ImageIO.read(input); byte[] data = ((DataBufferByte) image.getRaster().getDataBuffer()).getData(); Mat mat = new Mat(image.getHeight(), image.getWidth(), CvType.CV_8UC3); mat.put(0, 0, data); Mat mat1 = new Mat(image.getHeight(), image.getWidth(), CvType.CV_8UC1); Imgproc.cvtColor(mat, mat1, Imgproc.COLOR_RGB2GRAY); byte[] data1 = new byte[mat1.rows() * mat1.cols() * (int) (mat1.elemSize())]; mat1.get(0, 0, data1); BufferedImage image1 = new BufferedImage(mat1.cols(), mat1.rows(), BufferedImage.TYPE_BYTE_GRAY); image1.getRaster().setDataElements(0, 0, mat1.cols(), mat1.rows(), data1); File ouptut = new File("output\\grayscale_" + new Date().getTime() + ".jpg"); ImageIO.write(image1, "jpg", ouptut); } catch (Exception e) { System.out.println("Error: " + e.getMessage()); } }
public void writeImageToStream(OutputStream os, String fileName, BufferedImage img) { // if we get here we need to save the image from the memory try { // try to write image using the format of the filename extension int pos = fileName.lastIndexOf('.'); String ext = fileName.substring(pos + 1).toLowerCase(Locale.US); if (ext.equals("jpg") || ext.equals("jpeg")) ext = "JPG"; else ext = "PNG"; // circumvent security issues by disabling disk-based caching if (app.isApplet()) { javax.imageio.ImageIO.setUseCache(false); } ImageIO.write(img, ext, os); // restore caching to prevent side-effects if (app.isApplet()) { javax.imageio.ImageIO.setUseCache(true); } } catch (Exception e) { Application.debug(e.getMessage()); try { // if this did not work save image as png ImageIO.write(img, "png", os); } catch (Exception ex) { Application.debug(ex.getMessage()); return; } } }
public void run(String[] args) { File inDir = new File("input/SampleZoomLevel"); File outFile = new File("output/SampleZoomLevel/map.png"); File[] fileList = inDir.listFiles(); int i; // Stitching a map with 4 rows and 4 columns; the program is generalized, // so you can use higher multiples of 4, such as 8 by 8 and 16 by 16. int rows = 4; int cols = 4; int total = rows * cols; BufferedImage images[] = new BufferedImage[total]; try { for (i = 0; i < total; i++) { File inFile = fileList[i]; int c1; int c2; // The code below deals with the naming convention we use // for each map tile. // See the ReadMe for more on the naming convention. String s = inFile.getName().substring(0, 2); c1 = Integer.parseInt(s); s = inFile.getName().substring(3, 5); c2 = Integer.parseInt(s); BufferedImage image = null; image = ImageIO.read(inFile); images[c1 * cols + c2] = image; } } catch (IOException e) { System.err.println(e); System.exit(1); } // Our map tiles are square, with dimensions of 256 by 256 pixels. With 4 rows and //4 // columns, we create a 1024 by 1024 image. BufferedImage outputImage = new BufferedImage(256 * cols, 256 * rows, BufferedImage.TYPE_INT_ARGB_PRE); Graphics2D g = outputImage.createGraphics(); // Loop through the rows and columns for (i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { g.drawImage(images[i * cols + j], j * 256, i * 256, 256, 256, null); } } try { ImageIO.write(outputImage, "png", outFile); } catch (IOException e) { System.err.println(e); System.exit(1); } }
/** * Resize image bytes to a max width or height image size. * * @param inputBytes input image bytes * @param max max size * @return scaled image bytes * @throws IOException on error */ public static byte[] resizeImage(byte[] inputBytes, int max) throws IOException { BufferedImage inputImage = ImageIO.read(new ByteArrayInputStream(inputBytes)); BufferedImage outputImage = resizeImage(inputImage, max); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(outputImage, "jpg", baos); return baos.toByteArray(); }
public static BufferedImage encodeImage(String filename, int[] primes) { /* encodes a and b in the image using a sequence. * We are assuming that the image would be big enough * to hold the 16 bits */ BufferedImage img, newimg = null; int[] a = convertToBinary(primes[0], 8); int[] b = convertToBinary(primes[1], 8); int[] a_b = copyBits(a, b); // copy all bits into one array try { img = ImageIO.read(new File(imagePath + filename)); for (int i = 0; i < a_b.length; i++) { int p = img.getRGB(i, i); int[] bin = convertToBinary(p, 32); bin[0] = a_b[i]; int d = convertToDigit(bin, 32); img.setRGB(i, i, d); } ImageIO.write(img, "png", new File(imagePath + "new_" + filename)); newimg = ImageIO.read(new File(imagePath + "new_" + filename)); } catch (IOException e) { System.out.println("ERROR WRITING IMAGE...\n" + e.toString()); System.exit(1); } return newimg; }
private BufferedImage getImageIcon(String fileName) throws KettleException { InputStream inputStream = null; try { BufferedImage image = ImageIO.read(new File(fileName)); if (image == null) { image = ImageIO.read(new File("/" + fileName)); } if (image == null) { inputStream = getClass().getResourceAsStream(fileName); if (inputStream == null) { inputStream = getClass().getResourceAsStream("/" + fileName); } if (inputStream == null) { throw new KettleException("Unable to load image from file : '" + fileName + "'"); } image = ImageIO.read(inputStream); } WaitingImageObserver observer = new WaitingImageObserver(image); observer.waitImageLoaded(); return image; } catch (Throwable e) { throw new KettleException("Unable to load image from file : '" + fileName + "'", e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { throw new KettleException("Unable to close image reading stream", e); } } } }
public Rect(int x, int y, Color color, int width, int height, String bokstav_) { this.x = x; this.y = y; this.width = width; this.height = height; this.color = color; this.bokstav = bokstav_; this.alive = false; // ... Initiate Images try { image = ImageIO.read(this.getClass().getClassLoader().getResourceAsStream("Untitled-10.png")); } catch (IOException ex) { } try { alive_image = ImageIO.read(this.getClass().getClassLoader().getResourceAsStream("Untitled-12.png")); } catch (IOException ex) { } try { dead_image = ImageIO.read(this.getClass().getClassLoader().getResourceAsStream("Untitled-11.png")); } catch (IOException ex) { } }
/** * Compress and save an image to the disk. Currently this method only supports JPEG images. * * @param image The image to save * @param toFileName The filename to use * @param type The image type. Use <code>ImageUtils.IMAGE_JPEG</code> to save as JPEG images, or * <code>ImageUtils.IMAGE_PNG</code> to save as PNG. */ public static void saveCompressedImage(BufferedImage image, String toFileName, int type) { try { if (type == IMAGE_PNG) { throw new UnsupportedOperationException("PNG compression not implemented"); } Iterator iter = ImageIO.getImageWritersByFormatName("jpg"); ImageWriter writer; writer = (ImageWriter) iter.next(); ImageOutputStream ios = ImageIO.createImageOutputStream(new File(toFileName)); writer.setOutput(ios); ImageWriteParam iwparam = new JPEGImageWriteParam(Locale.getDefault()); iwparam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); iwparam.setCompressionQuality(0.7F); writer.write(null, new IIOImage(image, null, null), iwparam); ios.flush(); writer.dispose(); ios.close(); } catch (IOException e) { throw new ForumException(e); } }
/** loads the sprites to be used for the bots */ public static void loadSprites() { try { mainImageEast = ImageIO.read(new File("char/archer_east.png")); mainImageWest = ImageIO.read(new File("char/archer_west.png")); north = new BufferedImage[frameCount]; south = new BufferedImage[frameCount]; east = new BufferedImage[frameCount]; west = new BufferedImage[frameCount]; north_east = new BufferedImage[frameCount]; north_west = new BufferedImage[frameCount]; south_east = new BufferedImage[frameCount]; south_west = new BufferedImage[frameCount]; for (int i = 0; i < frameCount; i++) { north[i] = mainImageEast.getSubimage(0 * width, height * i, width, height); north_east[i] = mainImageEast.getSubimage(1 * width, height * i, width, height); east[i] = mainImageEast.getSubimage(2 * width, height * i, width, height); south_east[i] = mainImageEast.getSubimage(3 * width, height * i, width, height); south[i] = mainImageEast.getSubimage(4 * width, height * i, width, height); north_west[i] = mainImageWest.getSubimage(3 * width, height * i, width, height); west[i] = mainImageWest.getSubimage(2 * width, height * i, width, height); south_west[i] = mainImageWest.getSubimage(1 * width, height * i, width, height); } } catch (Exception e) { System.out.println("Spritesheet Not Found!"); } }
public byte[] picdecolour(String picid, String type, boolean profPic) { try { BufferedImage BI = ImageIO.read(new File("/var/tmp/instagrAndrew/" + picid)); BufferedImage processed = doTints(BI, this.tintValue, this.greyValue, false, profPic); if (this.contrastValue != 0f) { processed = doContrast(processed, this.contrastValue); } if (this.rotateValue != null) { processed = rotate(processed, rotateValue, null); } if (this.flipValue != null) { processed = rotate(processed, flipValue, null); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(processed, type, baos); baos.flush(); byte[] imageInByte = baos.toByteArray(); baos.close(); return imageInByte; } catch (IOException et) { } return null; }
/** * Loads an image from the supplied input stream. Supports formats supported by {@link ImageIO} * but not {@link FastImageIO}. */ protected static BufferedImage loadImage(InputStream iis) throws IOException { BufferedImage image; if (iis instanceof ImageInputStream) { image = ImageIO.read(iis); } else { // if we don't already have an image input stream, create a memory cache image input // stream to avoid causing freakout if we're used in a sandbox because ImageIO // otherwise use FileCacheImageInputStream which tries to create a temp file MemoryCacheImageInputStream mciis = new MemoryCacheImageInputStream(iis); image = ImageIO.read(mciis); try { // this doesn't close the underlying stream mciis.close(); } catch (IOException ioe) { // ImageInputStreamImpl.close() throws an IOException if it's already closed; // there's no way to find out if it's already closed or not, so we have to check // the exception message to determine if this is actually warning worthy if (!"closed".equals(ioe.getMessage())) { log.warning("Failure closing image input '" + iis + "'.", ioe); } } } // finally close our input stream StreamUtil.close(iis); return image; }
@Override protected void ensureContentAvailable() { if (!isContentAvailable()) { try { contentURL = createWadoURL(getMimeType(), -1); } catch (Exception e) { log.error("Unable to get image document WADO URL!", e); } try { Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName("dicom"); if (readers != null && readers.hasNext()) { List<org.dcm4chee.archive.entity.File> files = ((TCQueryLocal) JNDIUtils.lookup(TCQueryLocal.JNDI_NAME)) .findInstanceByUID(getSOPInstanceUID()) .getFiles(); String fsId = files.get(0).getFileSystem().getDirectoryPath(); String fileId = files.get(0).getFilePath(); ImageReader reader = readers.next(); reader.setInput( ImageIO.createImageInputStream( fsId.startsWith("tar:") ? TarRetrieveDelegate.getInstance().retrieveFileFromTar(fsId, fileId) : FileUtils.resolve(new File(fsId, fileId))), true); contentImage = reader.read(0); thumbnailImage = toThumbnailImage(contentImage); } } catch (Exception e) { log.error("Unable to convert encapsulated image to image!", e); } } }
@Test public void lossyWrite() throws Exception { File f = File.createTempFile("test-jpeg2000-lossy", ".jp2"); f.deleteOnExit(); Iterator<ImageWriter> writers = ImageIO.getImageWritersBySuffix("jp2"); assertTrue(writers.hasNext()); ImageWriter writer = writers.next(); J2KImageWriteParam writeParams = (J2KImageWriteParam) writer.getDefaultWriteParam(); writeParams.setLossless(false); writeParams.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); writeParams.setCompressionType("JPEG2000"); // writeParams.setFilter(J2KImageWriteParam.FILTER_97); writeParams.setCompressionQuality(0.0f); writeParams.setEncodingRate(0.5f); ImageOutputStream ios = ImageIO.createImageOutputStream(f); writer.setOutput(ios); writer.write(null, new IIOImage(image, null, null), writeParams); writer.dispose(); ios.close(); assertTrue("Expected file size < 1MB", f.length() < 128 * 1024); // System.out.println(f.length()); BufferedImage read = ImageIO.read(f); assertEquals(SIZE, read.getWidth()); }
public byte[] getThumbNail() { byte[] img = this.getImage(); byte[] out = null; ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream(); try { BufferedImage bufferedImage = ImageIO.read(new ByteArrayInputStream(img)); int w = bufferedImage.getWidth() / 10; int h = bufferedImage.getHeight() / 10; BufferedImage after = new BufferedImage(w, h, bufferedImage.getType()); AffineTransform at = new AffineTransform(); at.scale(0.1, 0.1); AffineTransformOp scaleOp = new AffineTransformOp(at, AffineTransformOp.TYPE_BILINEAR); after = scaleOp.filter(bufferedImage, after); ImageIO.write(after, "jpg", byteArrayOut); out = byteArrayOut.toByteArray(); } catch (IOException e) { e .printStackTrace(); // To change body of catch statement use File | Settings | File // Templates. } return out; }
@Test public void testImagesResizeJpg() { new PlayBuilder().build(); File folder = new File(Play.frameworkPath, "/framework/test-src/play/libs"); File source = new File(folder, "winie.jpg"); File result = new File(source.getParent(), "winie_testResult.jpg"); Images.resize(source, result, 1536, 2048); try { BufferedImage buffSrc = ImageIO.read(source); BufferedImage buffDest = ImageIO.read(result); assertEquals(buffSrc.getColorModel().hasAlpha(), buffDest.getColorModel().hasAlpha()); assertEquals(buffSrc.getColorModel().getPixelSize(), buffDest.getColorModel().getPixelSize()); assertEquals( buffSrc.getColorModel().getTransferType(), buffDest.getColorModel().getTransferType()); assertEquals( buffSrc.getColorModel().getTransparency(), buffDest.getColorModel().getTransparency()); } catch (IOException e) { fail("cannot compare the 2 images"); } finally { result.delete(); } }
public static void main(String[] args) throws IOException { File folder = new File( "C:\\Users\\smoeller\\Documents\\MSCS\\CS5542\\BigData-Spring2016-TourGuide\\BigData-Spring2016-TourGuide\\data\\"); File[] listOfFiles = folder.listFiles(); System.out.println("Total No of Files:" + listOfFiles.length); BufferedImage img = null; BufferedImage tempPNG = null; BufferedImage tempJPG = null; File newFilePNG = null; File newFileJPG = null; for (int i = 0; i < listOfFiles.length; i++) { if (listOfFiles[i].isFile()) { System.out.println("Resizing File " + folder.getPath() + listOfFiles[i].getName()); int pos = listOfFiles[i].getName().lastIndexOf("."); img = ImageIO.read(new File(folder.getPath() + listOfFiles[i].getName())); tempJPG = resizeImage(img, img.getWidth(), img.getHeight()); newFileJPG = new File(folder.getPath() + listOfFiles[i].getName().substring(0, pos) + "_New.jpg"); ImageIO.write(tempJPG, "jpg", newFileJPG); System.out.println(" Resized to " + newFileJPG); } } System.out.println("DONE"); }
/** * Save onscreen image to file - suffix must be png, jpg, or gif. * * @param filename the name of the file with one of the required suffixes */ public static void save(String filename) { File file = new File(filename); String suffix = filename.substring(filename.lastIndexOf('.') + 1); // png files if (suffix.toLowerCase().equals("png")) { try { ImageIO.write(onscreenImage, suffix, file); } catch (IOException e) { e.printStackTrace(); } } // need to change from ARGB to RGB for jpeg // reference: http://archives.java.sun.com/cgi-bin/wa?A2=ind0404&L=java2d-interest&D=0&P=2727 else if (suffix.toLowerCase().equals("jpg")) { WritableRaster raster = onscreenImage.getRaster(); WritableRaster newRaster; newRaster = raster.createWritableChild(0, 0, width, height, 0, 0, new int[] {0, 1, 2}); DirectColorModel cm = (DirectColorModel) onscreenImage.getColorModel(); DirectColorModel newCM = new DirectColorModel( cm.getPixelSize(), cm.getRedMask(), cm.getGreenMask(), cm.getBlueMask()); BufferedImage rgbBuffer = new BufferedImage(newCM, newRaster, false, null); try { ImageIO.write(rgbBuffer, suffix, file); } catch (IOException e) { e.printStackTrace(); } } else { System.out.println("Invalid image file type: " + suffix); } }
private BufferedImage getImage(File file) { ImageInputStream iis = null; BufferedImage image = null; try { iis = ImageIO.createImageInputStream(file); Iterator<ImageReader> it = ImageIO.getImageReaders(iis); if (!it.hasNext()) throw new UnsupportedOperationException("No image reader fround."); ImageReader reader = it.next(); reader.setInput(iis); int scaleFactor; if (reader.getWidth(0) >= reader.getHeight(0)) scaleFactor = Math.round(((float) reader.getWidth(0)) / MAX_SIZE); else scaleFactor = Math.round(((float) reader.getHeight(0)) / MAX_SIZE); ImageReadParam param = reader.getDefaultReadParam(); param.setSourceSubsampling(scaleFactor, scaleFactor, 0, 0); image = reader.read(0, param); } catch (IOException e) { e.printStackTrace(); } finally { if (iis != null) try { iis.close(); } catch (IOException e) { e.printStackTrace(); } } return image; }
@Override public void writeImage(RenderedImage image, String mimeType, float quality, OutputStream out) throws IOException { if ("image/jpeg".equals(mimeType)) { // Find a JPEG writer. ImageWriter writer = null; Iterator<ImageWriter> iter = ImageIO.getImageWritersByMIMEType(mimeType); if (iter.hasNext()) { writer = iter.next(); } JPEGImageWriteParam iwp = new JPEGImageWriteParam(null); iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); iwp.setCompressionQuality(quality); // Prepare output file. ImageOutputStream ios = ImageIO.createImageOutputStream(out); writer.setOutput(ios); // Write the image. writer.write(null, new IIOImage(image, null, null), iwp); // Cleanup. ios.flush(); writer.dispose(); ios.close(); } else { ImageIO.write(image, "png", out); } }
public Karte(Frontend frontend, D_Karte daten) { this.frontend = frontend; this.daten = daten; String pfadBild = "daten//felder"; String pfadRessource = "daten//ressourcen"; String pfadEinheit = "daten//einheiten"; String pfadStadt = "daten//stadt"; try { bildFeldGewaehlt = ImageIO.read(new File(pfadBild, "gewaehlt.png")); bildFeldMarkiert = ImageIO.read(new File(pfadBild, "markiert.png")); } catch (IOException e) { e.printStackTrace(); System.exit(-1); } dateienEinlesen(pfadBild, bildFeld); dateienEinlesen(pfadRessource, bildRessource); dateienEinlesen(pfadEinheit, bildEinheit); dateienEinlesen(pfadStadt, bildStadt); int spielfeldGroesse = frontend.getSpielfeldGroesse(); int zoomfaktor = frontend.getZoomfaktor(); int offset = spielfeldGroesse * zoomfaktor / 100; setLayout(null); setPreferredSize(new Dimension(getGroesseX() * offset, getGroesseY() * offset)); felder = new Feld[getGroesseX() + 1][getGroesseY() + 1]; for (int i = 1; i <= getGroesseX(); i++) { for (int j = 1; j <= getGroesseY(); j++) { Feld f = new Feld(frontend, i, j); felder[i][j] = f; add(f); } } }
/** * 将照片logo添加到二维码中间 * * @param image 生成的二维码照片对象 * @param imagePath 照片保存路径 * @param logoPath logo照片路径 * @param formate 照片格式 */ public static void overlapImage( BufferedImage image, String formate, String imagePath, String logoPath, MatrixToLogoImageConfig logoConfig) { try { BufferedImage logo = ImageIO.read(new File(logoPath)); Graphics2D g = image.createGraphics(); // 考虑到logo照片贴到二维码中,建议大小不要超过二维码的1/5; int width = image.getWidth() / logoConfig.getLogoPart(); int height = image.getHeight() / logoConfig.getLogoPart(); // logo起始位置,此目的是为logo居中显示 int x = (image.getWidth() - width) / 2; int y = (image.getHeight() - height) / 2; // 绘制图 g.drawImage(logo, x, y, width, height, null); // 给logo画边框 // 构造一个具有指定线条宽度以及 cap 和 join 风格的默认值的实心 BasicStroke g.setStroke(new BasicStroke(logoConfig.getBorder())); g.setColor(logoConfig.getBorderColor()); g.drawRect(x, y, width, height); g.dispose(); // 写入logo照片到二维码 ImageIO.write(image, formate, new File(imagePath)); } catch (Exception e) { e.printStackTrace(); } }
/* * create QR code with overlay */ public static void createQRCode( String qrCodeData, String outputFilePath, String overlayFilePath, String charset, Map<EncodeHintType, ErrorCorrectionLevel> hintMap, int qrCodeheight, int qrCodewidth) throws WriterException, IOException { // create QR code <BufferedImage> QRCodeWriter qrWriter = new QRCodeWriter(); BitMatrix matrix = qrWriter.encode(qrCodeData, BarcodeFormat.QR_CODE, qrCodewidth, qrCodeheight, hintMap); BufferedImage image = MatrixToImageWriter.toBufferedImage(matrix); // read overlay image BufferedImage overlay = ImageIO.read(new File(overlayFilePath)); // Draw the new image int deltaHeight = image.getHeight() - overlay.getHeight(); int deltaWidth = image.getWidth() - overlay.getWidth(); BufferedImage combined = new BufferedImage(qrCodeheight, qrCodewidth, BufferedImage.TYPE_INT_ARGB); Graphics2D g = (Graphics2D) combined.getGraphics(); g.drawImage(image, 0, 0, null); g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1f)); g.drawImage(overlay, (int) Math.round(deltaWidth / 2), (int) Math.round(deltaHeight / 2), null); ImageIO.write(combined, "PNG", new File(outputFilePath)); }
private void setup() throws IOException, UnsupportedAudioFileException, LineUnavailableException { startSounds(); tracker = new MediaTracker(this); fishImages[0] = ImageIO.read(getClass().getResourceAsStream("fish1.gif")); tracker.addImage(fishImages[0], 0); fishImages[1] = ImageIO.read(getClass().getResourceAsStream("fish2.gif")); tracker.addImage(fishImages[1], 0); aquariumImage = ImageIO.read(getClass().getResourceAsStream("tank.png")); tracker.addImage(aquariumImage, 0); try { tracker.waitForID(0); } catch (Exception ex) { System.out.println(ex.getMessage()); } setSize(aquariumImage.getWidth(this), aquariumImage.getHeight(this)); setResizable(true); setVisible(true); memoryImage = createImage(getSize().width, getSize().height); memoryGraphics = memoryImage.getGraphics(); }
private File getCachedImage(File file, int size) throws IOException { String md5 = DigestUtils.md5Hex(file.getPath()); File cachedImage = new File(getImageCacheDirectory(size), md5 + ".jpeg"); // Is cache missing or obsolete? if (!cachedImage.exists() || FileUtil.lastModified(file) > cachedImage.lastModified()) { InputStream in = null; OutputStream out = null; try { in = getImageInputStream(file); out = new FileOutputStream(cachedImage); BufferedImage image = ImageIO.read(in); if (image == null) { throw new Exception("Unable to decode image."); } image = scale(image, size, size); ImageIO.write(image, "jpeg", out); } catch (Throwable x) { // Delete corrupt (probably empty) thumbnail cache. LOG.warn("Failed to create thumbnail for " + file, x); IOUtils.closeQuietly(out); cachedImage.delete(); throw new IOException("Failed to create thumbnail for " + file + ". " + x.getMessage()); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } } return cachedImage; }
private <T> T scaleImageUsingAffineTransformation(final BufferedImage bufferedImage, T target) { BufferedImage destinationImage = generateDestinationImage(); Graphics2D graphics2D = destinationImage.createGraphics(); AffineTransform transformation = AffineTransform.getScaleInstance( ((double) getQualifiedWidth() / bufferedImage.getWidth()), ((double) getQualifiedHeight() / bufferedImage.getHeight())); graphics2D.drawRenderedImage(bufferedImage, transformation); graphics2D.addRenderingHints(retrieveRenderingHints()); try { if (target instanceof File) { LOGGER.info(String.format(M_TARGET_TYPE_OF, "File")); ImageIO.write(destinationImage, imageType.toString(), (File) target); } else if (target instanceof ImageOutputStream) { LOGGER.info(String.format(M_TARGET_TYPE_OF, "ImageOutputStream")); ImageIO.write(destinationImage, imageType.toString(), (ImageOutputStream) target); } else if (target instanceof OutputStream) { LOGGER.info(String.format(M_TARGET_TYPE_OF, "OutputStream")); ImageIO.write(destinationImage, imageType.toString(), (OutputStream) target); } else { target = null; } } catch (IOException e) { e.printStackTrace(); } return target; }
/** * 把图片印刷到图片上 * * @param pressImg -- 水印文件 * @param targetImg -- 目标文件 * @param x * @param y */ public static final void pressImage(String pressImg, String targetImg, int x, int y) { try { File _file = new File(targetImg); Image src = ImageIO.read(_file); int wideth = src.getWidth(null); int height = src.getHeight(null); BufferedImage image = new BufferedImage(wideth, height, BufferedImage.TYPE_INT_RGB); Graphics g = image.createGraphics(); g.drawImage(src, 0, 0, wideth, height, null); // 水印文件 File _filebiao = new File(pressImg); Image src_biao = ImageIO.read(_filebiao); int wideth_biao = src_biao.getWidth(null); int height_biao = src_biao.getHeight(null); g.drawImage( src_biao, wideth - wideth_biao - x, height - height_biao - y, wideth_biao, height_biao, null); // / g.dispose(); FileOutputStream out = new FileOutputStream(targetImg); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); encoder.encode(image); out.close(); } catch (Exception e) { e.printStackTrace(); } }