Java Examples for javax.imageio.stream.FileImageOutputStream
The following java examples will help you to understand the usage of javax.imageio.stream.FileImageOutputStream. These source code samples are taken from different open source projects.
Example 1
| Project: JDK-master File: RAFImageOutputStreamSpi.java View source code |
public ImageOutputStream createOutputStreamInstance(Object output, boolean useCache, File cacheDir) {
if (output instanceof RandomAccessFile) {
try {
return new FileImageOutputStream((RandomAccessFile) output);
} catch (Exception e) {
e.printStackTrace();
return null;
}
} else {
throw new IllegalArgumentException("input not a RandomAccessFile!");
}
}Example 2
| Project: AsciidocFX-master File: GifExporterFX.java View source code |
public ScheduledFuture<?> captureNow(Node target, Path outputDirectory, int timeBetweenFramesMS, boolean loopContinuously) throws Exception {
ImageOutputStream output = new FileImageOutputStream(outputDirectory.toFile());
GifSequenceWriter gifWriter = new GifSequenceWriter(output, 3, timeBetweenFramesMS, loopContinuously);
ScheduledFuture<?> future = threadService.scheduleWithDelay(() -> {
Semaphore semaphore = new Semaphore(1);
int w = (int) target.getBoundsInParent().getWidth();
int h = (int) target.getBoundsInParent().getHeight();
WritableImage img = new WritableImage(w, h);
threadService.runActionLater(() -> {
try {
target.snapshot(null, img);
BufferedImage bufferedImage = SwingFXUtils.fromFXImage(img, null);
threadService.runTaskLater(() -> {
boolean isSame = IOHelper.isSameImage(bufferedImage, latestBufferedImage);
latestBufferedImage = bufferedImage;
if (!isSame) {
try {
gifWriter.writeToSequence(bufferedImage);
} catch (IOException e) {
e.printStackTrace();
}
}
});
semaphore.release();
} catch (Exception ex) {
Logger.getLogger(GifExporterFX.class.getName()).log(Level.SEVERE, null, ex);
}
});
try {
semaphore.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
}, timeBetweenFramesMS, TimeUnit.MILLISECONDS);
threadService.start(() -> {
try {
future.get();
} catch (Exception e) {
}
IOHelper.close(gifWriter, output);
});
return future;
}Example 3
| Project: java-image-scaling-master File: Issue20.java View source code |
public void testScaleImage() throws Exception {
BufferedImage img = ImageIO.read(getClass().getResourceAsStream("issue20.jpg"));
ResampleOp resampleOp = new ResampleOp(DimensionConstrain.createMaxDimension(200, 200));
resampleOp.setUnsharpenMask(AdvancedResizeOp.UnsharpenMask.None);
BufferedImage rescaledImage = resampleOp.filter(img, null);
File file = new File("Issue20_scaled.jpeg");
ImageIO.write(rescaledImage, "jpg", file);
ImageOutputStream ios = new FileImageOutputStream(file);
ImageUtils.copyJpegMetaData(getClass().getResourceAsStream("issue20.jpg"), new FileInputStream(file), ios);
}Example 4
| Project: prime-arquillian-master File: PhotoCamView.java View source code |
public void oncapture(CaptureEvent captureEvent) {
filename = getRandomImageName();
byte[] data = captureEvent.getData();
ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
String newFileName = servletContext.getRealPath("") + File.separator + "resources" + File.separator + "demo" + File.separator + "images" + File.separator + "photocam" + File.separator + filename + ".png";
FileImageOutputStream imageOutput;
try {
imageOutput = new FileImageOutputStream(new File(newFileName));
imageOutput.write(data, 0, data.length);
imageOutput.close();
} catch (IOException e) {
throw new FacesException("Error in writing captured image.", e);
}
}Example 5
| Project: primefaces-showcase-clickstart-master File: PhotoShare.java View source code |
public void share(CaptureEvent captureEvent) {
String photo = getRandomImageName();
byte[] data = captureEvent.getData();
ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
String newFileName = servletContext.getRealPath("") + File.separator + "photocam" + File.separator + photo + ".png";
FileImageOutputStream imageOutput;
try {
imageOutput = new FileImageOutputStream(new File(newFileName));
imageOutput.write(data, 0, data.length);
imageOutput.close();
PushContextFactory.getDefault().getPushContext().push("/photoshare", photo + ".png");
} catch (Exception e) {
throw new FacesException("Error in writing captured image.");
}
}Example 6
| Project: primefaces-showcase-master File: PhotoCamBean.java View source code |
public void oncapture(CaptureEvent captureEvent) {
String photo = getRandomImageName();
this.photos.add(0, photo);
byte[] data = captureEvent.getData();
ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
String newFileName = servletContext.getRealPath("") + File.separator + "photocam" + File.separator + photo + ".png";
FileImageOutputStream imageOutput;
try {
imageOutput = new FileImageOutputStream(new File(newFileName));
imageOutput.write(data, 0, data.length);
imageOutput.close();
} catch (Exception e) {
throw new FacesException("Error in writing captured image.");
}
}Example 7
| Project: PrimefacesShowcase-master File: PhotoShare.java View source code |
public void share(CaptureEvent captureEvent) {
String photo = getRandomImageName();
byte[] data = captureEvent.getData();
ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
String newFileName = servletContext.getRealPath("") + File.separator + "photocam" + File.separator + photo + ".png";
FileImageOutputStream imageOutput;
try {
imageOutput = new FileImageOutputStream(new File(newFileName));
imageOutput.write(data, 0, data.length);
imageOutput.close();
PushContextFactory.getDefault().getPushContext().push("/photoshare", photo + ".png");
} catch (Exception e) {
throw new FacesException("Error in writing captured image.");
}
}Example 8
| Project: smartErp-master File: PhotoShare.java View source code |
public void share(CaptureEvent captureEvent) {
String photo = getRandomImageName();
byte[] data = captureEvent.getData();
ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
String newFileName = servletContext.getRealPath("") + File.separator + "photocam" + File.separator + photo + ".png";
FileImageOutputStream imageOutput;
try {
imageOutput = new FileImageOutputStream(new File(newFileName));
imageOutput.write(data, 0, data.length);
imageOutput.close();
RequestContext.getCurrentInstance().push("photoshare", photo + ".png");
} catch (Exception e) {
throw new FacesException("Error in writing captured image.");
}
}Example 9
| Project: 9-Patch-Resizer-master File: ImageWriter.java View source code |
public static void write(BufferedImage outputImage, Output output, File outputFile) throws IOException {
if (output == Output.JPG) {
// Need to strip alpha;
BufferedImage img = new BufferedImage(outputImage.getWidth(), outputImage.getHeight(), BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = img.createGraphics();
g2d.drawImage(outputImage, 0, 0, null);
g2d.dispose();
outputImage = img;
Iterator<javax.imageio.ImageWriter> itor = ImageIO.getImageWritersByFormatName("jpeg");
javax.imageio.ImageWriter writer = itor.next();
ImageWriteParam imageWriteParam = writer.getDefaultWriteParam();
imageWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
imageWriteParam.setCompressionQuality(0.9f);
FileImageOutputStream outputStream = new FileImageOutputStream(outputFile);
writer.setOutput(outputStream);
IIOImage image = new IIOImage(outputImage, null, null);
writer.write(null, image, imageWriteParam);
writer.dispose();
} else {
ImageIO.write(outputImage, output.getFormat(), outputFile);
}
}Example 10
| Project: ae-awt-master File: RAFImageOutputStreamSpi.java View source code |
public ImageOutputStream createOutputStreamInstance(Object output, boolean useCache, File cacheDir) {
if (output instanceof RandomAccessFile) {
try {
return new FileImageOutputStream((RandomAccessFile) output);
} catch (Exception e) {
e.printStackTrace();
return null;
}
} else {
throw new IllegalArgumentException("input not a RandomAccessFile!");
}
}Example 11
| Project: classlib6-master File: RAFImageOutputStreamSpi.java View source code |
public ImageOutputStream createOutputStreamInstance(Object output, boolean useCache, File cacheDir) {
if (output instanceof RandomAccessFile) {
try {
return new FileImageOutputStream((RandomAccessFile) output);
} catch (Exception e) {
e.printStackTrace();
return null;
}
} else {
throw new IllegalArgumentException("input not a RandomAccessFile!");
}
}Example 12
| Project: ikvm-openjdk-master File: RAFImageOutputStreamSpi.java View source code |
public ImageOutputStream createOutputStreamInstance(Object output, boolean useCache, File cacheDir) {
if (output instanceof RandomAccessFile) {
try {
return new FileImageOutputStream((RandomAccessFile) output);
} catch (Exception e) {
e.printStackTrace();
return null;
}
} else {
throw new IllegalArgumentException("input not a RandomAccessFile!");
}
}Example 13
| Project: jdk7u-jdk-master File: OutputTests.java View source code |
ImageOutputStream createImageOutputStream() throws IOException {
ImageOutputStream ios;
switch(outputType) {
case OUTPUT_FILE:
ios = new FileImageOutputStream((File) output);
break;
case OUTPUT_ARRAY:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
BufferedOutputStream bos = new BufferedOutputStream(baos);
if (ImageIO.getUseCache()) {
ios = new FileCacheImageOutputStream(bos, null);
} else {
ios = new MemoryCacheImageOutputStream(bos);
}
break;
case OUTPUT_FILECHANNEL:
FileOutputStream fos = new FileOutputStream((File) output);
origStream = fos;
java.nio.channels.FileChannel fc = fos.getChannel();
ios = fileChannelIOSSpi.createOutputStreamInstance(fc, false, null);
break;
default:
ios = null;
break;
}
return ios;
}Example 14
| Project: junrar-android-master File: RAFImageOutputStreamSpi.java View source code |
public ImageOutputStream createOutputStreamInstance(Object output, boolean useCache, File cacheDir) {
if (output instanceof RandomAccessFile) {
try {
return new FileImageOutputStream((RandomAccessFile) output);
} catch (Exception e) {
e.printStackTrace();
return null;
}
} else {
throw new IllegalArgumentException("input not a RandomAccessFile!");
}
}Example 15
| Project: ManagedRuntimeInitiative-master File: OutputTests.java View source code |
ImageOutputStream createImageOutputStream() throws IOException {
ImageOutputStream ios;
switch(outputType) {
case OUTPUT_FILE:
ios = new FileImageOutputStream((File) output);
break;
case OUTPUT_ARRAY:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
BufferedOutputStream bos = new BufferedOutputStream(baos);
if (ImageIO.getUseCache()) {
ios = new FileCacheImageOutputStream(bos, null);
} else {
ios = new MemoryCacheImageOutputStream(bos);
}
break;
case OUTPUT_FILECHANNEL:
FileOutputStream fos = new FileOutputStream((File) output);
origStream = fos;
java.nio.channels.FileChannel fc = fos.getChannel();
ios = fileChannelIOSSpi.createOutputStreamInstance(fc, false, null);
break;
default:
ios = null;
break;
}
return ios;
}Example 16
| Project: openjdk-master File: OutputTests.java View source code |
ImageOutputStream createImageOutputStream() throws IOException {
ImageOutputStream ios;
switch(outputType) {
case OUTPUT_FILE:
ios = new FileImageOutputStream((File) output);
break;
case OUTPUT_ARRAY:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
BufferedOutputStream bos = new BufferedOutputStream(baos);
if (ImageIO.getUseCache()) {
ios = new FileCacheImageOutputStream(bos, null);
} else {
ios = new MemoryCacheImageOutputStream(bos);
}
break;
case OUTPUT_FILECHANNEL:
FileOutputStream fos = new FileOutputStream((File) output);
origStream = fos;
java.nio.channels.FileChannel fc = fos.getChannel();
ios = fileChannelIOSSpi.createOutputStreamInstance(fc, false, null);
break;
default:
ios = null;
break;
}
return ios;
}Example 17
| Project: openjdk8-jdk-master File: OutputTests.java View source code |
ImageOutputStream createImageOutputStream() throws IOException {
ImageOutputStream ios;
switch(outputType) {
case OUTPUT_FILE:
ios = new FileImageOutputStream((File) output);
break;
case OUTPUT_ARRAY:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
BufferedOutputStream bos = new BufferedOutputStream(baos);
if (ImageIO.getUseCache()) {
ios = new FileCacheImageOutputStream(bos, null);
} else {
ios = new MemoryCacheImageOutputStream(bos);
}
break;
case OUTPUT_FILECHANNEL:
FileOutputStream fos = new FileOutputStream((File) output);
origStream = fos;
java.nio.channels.FileChannel fc = fos.getChannel();
ios = fileChannelIOSSpi.createOutputStreamInstance(fc, false, null);
break;
default:
ios = null;
break;
}
return ios;
}Example 18
| Project: robocode-master File: ScreenshotUtil.java View source code |
public static void saveScreenshot(BufferedImage screenshot, String format, float compressionQuality) {
FileImageOutputStream output = null;
ImageWriter writer = null;
File screenshotDir = FileUtil.getScreenshotsDir();
FileUtil.createDir(screenshotDir);
File file = new File(screenshotDir, DATE_FORMAT.format(new Date()) + '.' + format.toLowerCase());
try {
// Instantiate an ImageWriteParam object with default compression options
Iterator<ImageWriter> it = ImageIO.getImageWritersByFormatName(format);
writer = (ImageWriter) it.next();
ImageWriteParam iwp = writer.getDefaultWriteParam();
// If compression is supported, then set the compression mode
if (iwp.canWriteCompressed()) {
// Use explicit compression mode
iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
// Set compression quality, where 1 specifies minimum compression and maximum quality
// float between 0 and 1
iwp.setCompressionQuality(compressionQuality);
}
// Write the screen shot to file
output = new FileImageOutputStream(file);
writer.setOutput(output);
IIOImage image = new IIOImage(screenshot, null, null);
writer.write(null, image, iwp);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (writer != null) {
writer.dispose();
}
if (output != null) {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}Example 19
| Project: roboyuddh-master File: ScreenshotUtil.java View source code |
public static void saveScreenshot(BufferedImage screenshot, String format, float compressionQuality) {
FileImageOutputStream output = null;
ImageWriter writer = null;
File screenshotDir = FileUtil.getScreenshotsDir();
FileUtil.createDir(screenshotDir);
File file = new File(screenshotDir, DATE_FORMAT.format(new Date()) + '.' + format.toLowerCase());
try {
// Instantiate an ImageWriteParam object with default compression options
Iterator<ImageWriter> it = ImageIO.getImageWritersByFormatName(format);
writer = (ImageWriter) it.next();
ImageWriteParam iwp = writer.getDefaultWriteParam();
// If compression is supported, then set the compression mode
if (iwp.canWriteCompressed()) {
// Use explicit compression mode
iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
// Set compression quality, where 1 specifies minimum compression and maximum quality
// float between 0 and 1
iwp.setCompressionQuality(compressionQuality);
}
// Write the screen shot to file
output = new FileImageOutputStream(file);
writer.setOutput(output);
IIOImage image = new IIOImage(screenshot, null, null);
writer.write(null, image, iwp);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (writer != null) {
writer.dispose();
}
if (output != null) {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}Example 20
| Project: SRE-RoboCode-master File: ScreenshotUtil.java View source code |
public static void saveScreenshot(BufferedImage screenshot, String format, float compressionQuality) {
FileImageOutputStream output = null;
ImageWriter writer = null;
File screenshotDir = FileUtil.getScreenshotsDir();
FileUtil.createDir(screenshotDir);
File file = new File(screenshotDir, DATE_FORMAT.format(new Date()) + '.' + format.toLowerCase());
try {
// Instantiate an ImageWriteParam object with default compression options
Iterator<ImageWriter> it = ImageIO.getImageWritersByFormatName(format);
writer = (ImageWriter) it.next();
ImageWriteParam iwp = writer.getDefaultWriteParam();
// If compression is supported, then set the compression mode
if (iwp.canWriteCompressed()) {
// Use explicit compression mode
iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
// Set compression quality, where 1 specifies minimum compression and maximum quality
// float between 0 and 1
iwp.setCompressionQuality(compressionQuality);
}
// Write the screen shot to file
output = new FileImageOutputStream(file);
writer.setOutput(output);
IIOImage image = new IIOImage(screenshot, null, null);
writer.write(null, image, iwp);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (writer != null) {
writer.dispose();
}
if (output != null) {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}Example 21
| Project: AXON-E-Tools-master File: ImageScalerAWT.java View source code |
@Override
public void scale(Path outPath, Path imagePath, Optional<Path> watermarkPath, int size, boolean hq) throws IOException {
// Read in
BufferedImage inImage;
try {
synchronized (// Prevent problems with liblcms2-2
imageioLock) {
inImage = ImageIO.read(imagePath.toFile());
}
} catch (Throwable e) {
throw new IOException("Cannot read: " + imagePath, e);
}
// Make watermark
if (watermarkPath.isPresent()) {
BufferedImage watermarkImage;
try {
synchronized (// Prevent problems with liblcms2-2
imageioLock) {
watermarkImage = ImageIO.read(watermarkPath.get().toFile());
}
} catch (IOException e) {
throw new IOException("Cannot read watermark: " + watermarkPath.get(), e);
}
int ww = watermarkImage.getWidth();
int wh = watermarkImage.getHeight();
int iw = inImage.getWidth();
int ih = inImage.getHeight();
Graphics2D drawGraphics = inImage.createGraphics();
drawGraphics.drawImage(watermarkImage, iw - ww, ih - wh, ww, wh, null);
}
// Scale
Dim d = mkOuterbox(size, inImage.getWidth(), inImage.getHeight());
BufferedImage resultImage = new BufferedImage(d.w, d.h, BufferedImage.TYPE_INT_RGB);
Image scaled = inImage.getScaledInstance(d.w, d.h, Image.SCALE_SMOOTH);
Graphics2D g2 = resultImage.createGraphics();
g2.drawImage(scaled, 0, 0, d.w, d.h, null);
// Quality can be higher for smaller images
float quality;
if (hq) {
quality = 1f;
} else {
if (size <= 200) {
quality = .9f;
} else if (size <= 400) {
quality = .7f;
} else if (size <= 700) {
quality = .5f;
} else {
quality = .4f;
}
}
// ImageIO.write( resultImage, "jpeg", cache );
// Code from:
// http://www.universalwebservices.net/web-programming-resources/java/adjust-jpeg-image-compression-quality-when-saving-images-in-java
// Let you choose compression level
Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName("jpeg");
ImageWriter writer = iter.next();
ImageWriteParam iwp = writer.getDefaultWriteParam();
iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
iwp.setProgressiveMode(ImageWriteParam.MODE_DEFAULT);
iwp.setCompressionQuality(quality);
IIOImage image = new IIOImage(resultImage, null, null);
try (FileImageOutputStream output = new FileImageOutputStream(outPath.toFile())) {
writer.setOutput(output);
synchronized (// Just in case writing is as buggy as reading
imageioLock) {
writer.write(null, image, iwp);
}
}
}Example 22
| Project: dawn-third-master File: ILBMEncoder.java View source code |
public void write(File f, BitmapImage img, int camg) throws IOException {
IFFOutputStream out = null;
try {
out = new IFFOutputStream(new FileImageOutputStream(f));
out.pushCompositeChunk("FORM", "ILBM");
writeBMHD(out, img);
writeCMAP(out, img);
writeCAMG(out, camg);
writeBODY(out, img);
out.popChunk();
} finally {
if (out != null) {
out.close();
}
}
}Example 23
| Project: FlightPlot-master File: PlotExportDialog.java View source code |
private void onOK() {
String format = ((String) formatComboBox.getSelectedItem()).toLowerCase();
JFileChooser fc = new JFileChooser();
if (lastExportDirectory != null) {
fc.setCurrentDirectory(lastExportDirectory);
}
FileNameExtensionFilter extensionFilter = new FileNameExtensionFilter(format.toUpperCase() + " Image (*." + format + ")", format);
fc.setFileFilter(extensionFilter);
fc.setDialogTitle("Export Plot");
int returnVal = fc.showDialog(null, "Export Plot");
if (returnVal == JFileChooser.APPROVE_OPTION) {
lastExportDirectory = fc.getCurrentDirectory();
String fileName = fc.getSelectedFile().toString();
if (extensionFilter == fc.getFileFilter() && !fileName.toLowerCase().endsWith("." + format)) {
fileName += "." + format;
}
try {
int width = Integer.parseInt(widthField.getText());
int height = Integer.parseInt(heightField.getText());
BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = img.createGraphics();
double scale = Double.parseDouble(scaleField.getText());
AffineTransform st = AffineTransform.getScaleInstance(scale, scale);
g2.transform(st);
app.getChart().draw(g2, new Rectangle2D.Double(0.0D, 0.0D, width / scale, height / scale), null, null);
g2.dispose();
ImageWriter imgWriter = ImageIO.getImageWritersByFormatName(format).next();
ImageWriteParam imgWriteParam = imgWriter.getDefaultWriteParam();
if ("jpg".equals(format)) {
imgWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
imgWriteParam.setCompressionQuality(1.0f);
}
ImageOutputStream outputStream = new FileImageOutputStream(new File(fileName));
imgWriter.setOutput(outputStream);
IIOImage outputImage = new IIOImage(img, null, null);
imgWriter.write(null, outputImage, imgWriteParam);
imgWriter.dispose();
app.setStatus(String.format("Exported to \"%s\"", fileName));
} catch (Exception e) {
app.setStatus("Error: " + e);
e.printStackTrace();
}
}
dispose();
}Example 24
| Project: geoserver-2.0.x-master File: ThumbnailStorage.java View source code |
private void writeResized(BufferedImage image, double scale, ImageWriter format, String name, File root) throws IOException {
BufferedImage scaledImage = null;
if (Math.abs(scale - 1.0) > 0.001) {
AffineTransform xform = AffineTransform.getScaleInstance(scale, scale);
AffineTransformOp op = new AffineTransformOp(xform, AffineTransformOp.TYPE_BILINEAR);
Rectangle2D dim = op.getBounds2D(image);
scaledImage = new BufferedImage((int) dim.getMaxX(), (int) dim.getMaxY(), image.getType());
scaledImage = op.filter(image, scaledImage);
} else {
scaledImage = image;
}
File f = new File(root, name);
ImageOutputStream out = new FileImageOutputStream(f);
format.setOutput(out);
format.write(scaledImage);
out.flush();
out.close();
}Example 25
| Project: geotoolkit-master File: TestTiffImageReaderWriter.java View source code |
/**
* Create an image with expected properties given by followed attributs : <br/>
* - random width and height<br/>
* - sampleBitsSize<br/>
* - numBand<br/>
* - photometricInterpretation<br/>
* - sampleFormat<br/>
* and fill it by appropriate random sample values.<br/>
* Then image is writen at "filetest" adress and read.<br/>
* To finish read image is compare to itself before writing.<br/><br/>
*
* Moreover, test different input / output type setted.
*
* @param message in case of assertion error.
* @param fileTest the place to be.
* @param sampleBitsSize sample bit number.
* @param numBand band number.
* @param photometricInterpretation define RGB or 1 band or also color map.
* @param sampleFormat define sample format integer or floating point.
* @see #PHOTOMETRIC_MINISBLACK
* @see #PHOTOMETRIC_PALETTE
* @see #PHOTOMETRIC_RGB
* @see #SAMPLEFORMAT_IEEEFP
* @see #SAMPLEFORMAT_UINT
* @throws IOException if problem during reading/writing action.
*/
private void defaultTest(final String message, final Path fileTest, final SampleType sampleType, final int numBand, final PhotometricInterpretation photometricInterpretation) throws IOException {
final int width = random.nextInt(256) + 16;
final int height = random.nextInt(256) + 16;
final RenderedImage expected = createImageTest(width, height, sampleType, numBand, photometricInterpretation);
String messageSize = message + "\n Test image size(w/h) " + width + "/" + height + ".";
//test writing with different output type from Spi
for (Class type : writer.getOriginatingProvider().getOutputTypes()) {
Object out = null;
try {
if (type.equals(Path.class)) {
out = fileTest;
} else if (type.equals(File.class)) {
out = fileTest.toFile();
} else if (type.equals(String.class)) {
out = fileTest.toString();
} else if (type.equals(OutputStream.class)) {
out = Files.newOutputStream(fileTest, StandardOpenOption.CREATE, StandardOpenOption.WRITE);
} else if (type.equals(ImageOutputStream.class)) {
out = CoverageIO.createImageOutputStream(fileTest);
} else if (type.equals(FileOutputStream.class)) {
out = new FileImageOutputStream(fileTest.toFile());
}
//-- to initialize writer
writer.setOutput(out);
writer.write(expected, writerParam);
writer.dispose();
//close if output is a closable stream
if (out != null && !IOUtilities.canProcessAsPath(out) && out instanceof Closeable) {
((Closeable) out).close();
}
//test image (read using Path input)
//-- to initialize reader
reader.setInput(fileTest);
final RenderedImage tested = reader.read(0);
reader.close();
//test image
checkImage(messageSize, expected, tested);
} catch (Exception e) {
String messageType = messageSize + "\n Writer output : " + type.getCanonicalName() + "\n Reader input : " + fileTest.getClass().getCanonicalName() + "." + "\n Cause : " + e.getMessage();
fail(messageType);
}
}
//test reading with every reader spy inputTypes (except Path because already tested)
for (Class type : reader.getOriginatingProvider().getInputTypes()) {
Object in = null;
try {
if (type.equals(File.class)) {
in = fileTest.toFile();
} else if (type.equals(String.class)) {
in = fileTest.toString();
} else if (type.equals(InputStream.class)) {
in = Files.newInputStream(fileTest);
} else if (type.equals(ImageInputStream.class)) {
in = CoverageIO.createImageInputStream(fileTest);
}
//-- to initialize reader
reader.setInput(fileTest);
final RenderedImage tested = reader.read(0);
reader.close();
//close if input is a closable stream
if (in != null && !IOUtilities.canProcessAsPath(in) && in instanceof Closeable) {
((Closeable) in).close();
}
//test image
checkImage(messageSize, expected, tested);
} catch (Exception e) {
String messageType = messageSize + "\n Reader input : " + type.getCanonicalName() + "." + "\n Cause : " + e.getMessage();
fail(messageType);
}
}
}Example 26
| Project: kontempl-master File: ImageUtils.java View source code |
public static String convertImageToJpeg(File imgFile, String suffix, String path) throws BadImageException {
int pos = imgFile.getName().lastIndexOf(".");
String existingName = imgFile.getName();
String newName = existingName.substring(0, pos) + ".jpg";
logger.debug("new name: " + newName);
String newPath = path + File.separator + newName;
logger.debug("new Path: " + newPath);
BufferedImage image = null;
ImageOutputStream outStream = null;
Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName("jpeg");
ImageWriter writer = null;
if (iter.hasNext())
writer = iter.next();
if (writer == null) {
logger.error("No JPEG image writers - fatal error");
throw new BadImageException("No JPEG image writers found");
}
// adjust JPEG output quality
ImageWriteParam iwp = writer.getDefaultWriteParam();
iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
iwp.setCompressionQuality(0.95f);
iwp.setProgressiveMode(ImageWriteParam.MODE_DEFAULT);
try {
outStream = new FileImageOutputStream(new File(newPath));
image = ImageIO.read(imgFile);
writer.setOutput(outStream);
IIOImage outImage = new IIOImage(image, null, null);
writer.write(null, outImage, iwp);
} catch (IOException e) {
logger.warn("Error reading -> writing: " + imgFile.getAbsolutePath(), e);
throw new BadImageException("Error transcoding image file: " + imgFile.getAbsolutePath() + ", Exception: " + e);
} finally {
writer.dispose();
try {
assert outStream != null;
outStream.close();
} catch (IOException e) {
logger.error("Cannot close output stream: " + e);
}
}
return newName;
}Example 27
| Project: selenium-utils-master File: ILBMEncoder.java View source code |
public void write(File f, BitmapImage img, int camg) throws IOException {
IFFOutputStream out = null;
try {
out = new IFFOutputStream(new FileImageOutputStream(f));
out.pushCompositeChunk("FORM", "ILBM");
writeBMHD(out, img);
writeCMAP(out, img);
writeCAMG(out, camg);
writeBODY(out, img);
out.popChunk();
} finally {
if (out != null) {
out.close();
}
}
}Example 28
| Project: sprout-master File: ExportGifAction.java View source code |
public void saveImage(File saveFile) throws Exception {
int width = (int) controller.getBoardRenderer().getRendererBounds().getWidth();
width = Math.min(width, controller.getScrollPanel().getViewportSize().width);
int height = width * 9 / 16;
BufferedImage firstImage = controller.getImageManager().getCroppedExportImage(width, height);
// create a new BufferedOutputStream with the last argument
ImageOutputStream output = new FileImageOutputStream(saveFile);
// create a gif sequence with the type of the first image, 1 second
// between frames, which loops continuously
GifSequenceWriter writer = new GifSequenceWriter(output, firstImage.getType(), 1, true);
// write out the first image to our sequence...
writer.writeToSequence(firstImage);
for (int i = 0; i < 200; i++) {
int skipFrames = 4;
if (controller.getBoardRenderer().getBlockSize() == 4) {
skipFrames = 2;
}
if (controller.getBoardRenderer().getBlockSize() > 4) {
skipFrames = 1;
}
for (int j = 0; j < skipFrames; j++) {
controller.getInteractionLock().writeLock().lock();
controller.getGameModel().performGameStep();
controller.getInteractionLock().writeLock().unlock();
controller.getImageManager().repaintNewImage();
}
BufferedImage nextImage = controller.getImageManager().getCroppedExportImage(width, height);
writer.writeToSequence(nextImage);
}
writer.close();
output.close();
}Example 29
| Project: SproutLife-master File: ExportGifAction.java View source code |
public void saveImage(File saveFile) throws Exception {
int width = (int) controller.getBoardRenderer().getRendererBounds().getWidth();
width = Math.min(width, controller.getScrollPanel().getViewportSize().width);
int height = width * 9 / 16;
BufferedImage firstImage = controller.getImageManager().getCroppedExportImage(width, height);
// create a new BufferedOutputStream with the last argument
ImageOutputStream output = new FileImageOutputStream(saveFile);
// create a gif sequence with the type of the first image, 1 second
// between frames, which loops continuously
GifSequenceWriter writer = new GifSequenceWriter(output, firstImage.getType(), 1, true);
// write out the first image to our sequence...
writer.writeToSequence(firstImage);
for (int i = 0; i < 200; i++) {
int skipFrames = 4;
if (controller.getBoardRenderer().getBlockSize() == 4) {
skipFrames = 2;
}
if (controller.getBoardRenderer().getBlockSize() > 4) {
skipFrames = 1;
}
for (int j = 0; j < skipFrames; j++) {
controller.getInteractionLock().writeLock().lock();
controller.getGameModel().performGameStep();
controller.getInteractionLock().writeLock().unlock();
controller.getImageManager().repaintNewImage();
}
BufferedImage nextImage = controller.getImageManager().getCroppedExportImage(width, height);
writer.writeToSequence(nextImage);
}
writer.close();
output.close();
}Example 30
| Project: Weasis-master File: NativeImage.java View source code |
public static void writeByteBuffer(ImageOutputStream ouputStream, ByteBuffer outBuf, int bytesWritten) throws IOException {
if (ouputStream instanceof FileImageOutputStream) {
try (RandomAccessFile raf = FileStreamSegment.getRandomAccessFile((FileImageOutputStream) ouputStream)) {
raf.getChannel().write(outBuf);
}
} else {
if (outBuf.hasArray()) {
ouputStream.write(outBuf.array(), 0, bytesWritten);
} else {
int limit = outBuf.limit() - outBuf.position();
if (limit > bytesWritten) {
limit = bytesWritten;
}
for (int i = 0; i < limit; i++) {
ouputStream.write(outBuf.get());
}
}
}
}Example 31
| Project: AnalyseSI-master File: MCDPanel.java View source code |
public void actionPerformed(ActionEvent e) {
String action = e.getActionCommand();
if (action.equals(Constantes.ADD_ENT)) {
typeAction = Constantes.ADD_ENT;
mcdComponent.setEnabled(false);
deselectToolbarButton((JToggleButton) e.getSource());
}
if (action.equals(Constantes.ADD_ASS)) {
typeAction = Constantes.ADD_ASS;
mcdComponent.setEnabled(false);
deselectToolbarButton((JToggleButton) e.getSource());
}
if (action.equals(Constantes.ADD_LIEN)) {
typeAction = Constantes.ADD_LIEN;
mcdComponent.setEnabled(true);
deselectToolbarButton((JToggleButton) e.getSource());
if (btnLien.getSelectedObjects() != null)
mcdComponent.addLien();
}
if (action.equals(Constantes.CHANGE_CURSEUR)) {
typeAction = Constantes.CHANGE_CURSEUR;
mcdComponent.annulerCreerLien();
mcdComponent.setEnabled(true);
deselectToolbarButton((JToggleButton) e.getSource());
}
if (action.equals(Constantes.DEL_LIEN)) {
String mess = Utilities.getLangueMessage("supprimer_lien_selection");
if (JOptionPane.showConfirmDialog(null, mess, Utilities.getLangueMessage("analysesi"), JOptionPane.YES_NO_OPTION) != JOptionPane.YES_OPTION)
return;
mcdComponent.removeLien();
}
if (action.equals(Constantes.DEL_OBJET)) {
deleteObjects();
}
if (action.equals(Constantes.MOD_OBJET)) {
entiteDialog.load(objet);
}
if (action.equals(Constantes.MOD_LIEN)) {
lienDialog.load(lien);
}
if (action.equals(Constantes.VERIF_MCD)) {
mcdComponent.isCorrect(Constantes.SHOW_ALL);
}
if (action.equals(Constantes.BUILD_MPD)) {
if (mcdComponent.buildMPD(mpdComponent, Constantes.CREATE_MCD)) {
mpdComponent.buildSQL(mcdComponent.getData(), sqlCommand);
mldComponent.buildMLD(mpdComponent, mldCommand);
}
}
if (action.equals(Constantes.SAVE_GRAPH)) {
String fileName = chooseFile();
if (fileName == null)
return;
if (!Utilities.getExtension(fileName).equals(Constantes.PNG_MINUSCULE) && !Utilities.getExtension(fileName).equals(Constantes.PNG))
fileName = fileName + "." + Constantes.PNG_MINUSCULE;
mcdComponent.enleverFocus();
try {
File imageFile;
FileImageOutputStream outputStream;
BufferedImage img;
Graphics g;
Graphics2D g2d;
Rectangle2D r;
imageFile = new File(fileName);
img = new BufferedImage((int) (mcdComponent.getPreferredSize().getWidth()), (int) (mcdComponent.getPreferredSize().getHeight()), BufferedImage.TYPE_INT_RGB);
g = img.getGraphics();
g2d = (Graphics2D) g;
g2d.setColor(new Color(255, 255, 255));
r = new Rectangle2D.Double(0, 0, img.getWidth(), img.getHeight());
g2d.fill(r);
mcdComponent.paintComponent(g2d);
PNGImageWriter writer = new PNGImageWriter(null);
writer.setOutput(outputStream = new FileImageOutputStream(imageFile));
writer.write(img);
outputStream.close();
writer.dispose();
} catch (IOException err) {
GUIUtilities.error("Impossible de sauvegarder le fichier " + fileName);
}
}
}Example 32
| Project: Chromecast-Backgrounds-master File: Images.java View source code |
/**
* Save an image as a JPG with a specified quality setting..
* @param image The image object to save.
* @param path Path to save the file as, including the file name and extension.
* @param quality Image quality in the range 0.0-1.0. 1.0 is least compression, best quality.
* @return True if the image was saved, false if an error occurred.
*/
public static Boolean saveImageAsJpg(BufferedImage image, String path, float quality) {
Boolean success = false;
ImageWriter writer = ImageIO.getImageWritersByFormatName("jpeg").next();
ImageWriteParam param = writer.getDefaultWriteParam();
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
param.setCompressionQuality(quality);
try {
File outFile = new File(path);
FileImageOutputStream output = new FileImageOutputStream(outFile);
writer.setOutput(output);
IIOImage outImage = new IIOImage(image, null, null);
writer.write(null, outImage, param);
writer.dispose();
success = true;
} catch (IOException e) {
e.printStackTrace();
}
return success;
}Example 33
| Project: Density-master File: ImageHandler.java View source code |
private void compressJpeg(BufferedImage bufferedImage, CompoundDirectory exif, float quality, File targetFile) throws IOException {
ImageWriter jpgWriter = ImageIO.getImageWritersByFormatName("jpg").next();
ImageWriteParam jpgWriteParam = jpgWriter.getDefaultWriteParam();
jpgWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
jpgWriteParam.setCompressionQuality(quality);
ImageWriter writer = null;
try (ImageOutputStream outputStream = new FileImageOutputStream(targetFile)) {
writer = ImageIO.getImageWritersByFormatName("jpg").next();
writer.setOutput(outputStream);
writer.write(null, new IIOImage(bufferedImage, null, null), jpgWriteParam);
} finally {
if (writer != null)
writer.dispose();
}
}Example 34
| Project: imageio-ext-master File: JP2KKakaduWriteTest.java View source code |
public void testOutputStream() throws IOException {
if (!isKakaduAvailable) {
LOGGER.warning("Kakadu libs not found: test are skipped ");
return;
}
final File outFile = File.createTempFile("stream", "temp");
final FileImageOutputStream stream = new FileImageOutputStream(outFile);
stream.writeBytes("This is an Image Header written before the j2c raw codestream");
final ImageReader reader = new BMPImageReaderSpi().createReaderInstance();
final File file = TestData.file(this, "RGB24.bmp");
reader.setInput(ImageIO.createImageInputStream(file));
BufferedImage bi = reader.read(0);
final ImageWriter writer = new JP2KKakaduImageWriterSpi().createWriterInstance();
JP2KKakaduImageWriteParam param = new JP2KKakaduImageWriteParam();
param.setQuality(0.8);
param.setWriteCodeStreamOnly(true);
writer.setOutput(stream);
writer.write(null, new IIOImage(bi, null, null), param);
writer.dispose();
LOGGER.info(writeOperations + " write operations performed");
}Example 35
| Project: infoglue-master File: Imaging.java View source code |
public static void resize(File input, File output, int width, int height, String format, boolean constrainProportions, float quality) throws Exception {
if (quality > 1)
quality = quality / 100;
BufferedImage image = javax.imageio.ImageIO.read(input);
Mode mode = Mode.AUTOMATIC;
if (height <= 0) {
height = width;
mode = Mode.FIT_TO_WIDTH;
}
if (width <= 0) {
width = height;
mode = Mode.FIT_TO_HEIGHT;
}
logger.info("image:" + image.getType() + ":" + BufferedImage.TYPE_CUSTOM);
if (image.getType() == BufferedImage.TYPE_CUSTOM) {
BufferedImage image_to_save2 = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_RGB);
image_to_save2.getGraphics().drawImage(image, 0, 0, null);
image = image_to_save2;
}
BufferedImage scaledImage = null;
if (constrainProportions) {
scaledImage = Scalr.resize(image, mode, width, height);
//scaledImage = Scalr.resize(image, width, height);
} else {
scaledImage = Scalr.resize(image, width, height);
}
//javax.imageio.ImageIO.write(scaledImage, format, output);
Iterator iter = ImageIO.getImageWritersByFormatName("jpeg");
ImageWriter writer = (ImageWriter) iter.next();
ImageWriteParam iwp = writer.getDefaultWriteParam();
iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
iwp.setCompressionQuality(quality);
//output.getParentFile().mkdirs();
FileImageOutputStream outputStream = new FileImageOutputStream(output);
writer.setOutput(outputStream);
IIOImage ioImage = new IIOImage(scaledImage, null, null);
writer.write(null, ioImage, iwp);
writer.dispose();
}Example 36
| Project: korsakow-editor-master File: JavaImageIOImageEncoder.java View source code |
public void encode(File sourceFile, ImageFormat dstFormat, File destFile) throws ImageEncoderException {
BufferedImage image;
try {
image = ImageIO.read(sourceFile);
} catch (IOException e) {
throw new ImageEncoderException(e);
}
if (width != null && height != null) {
image = getScaledInstance(image, width, height, RenderingHints.VALUE_INTERPOLATION_BICUBIC, false);
}
try {
if (!ImageIO.getImageWritersByFormatName(getFormatName(dstFormat)).hasNext())
throw new ImageEncoderException("No Image writer for : " + getFormatName(dstFormat));
ImageWriter writer = ImageIO.getImageWritersByFormatName(getFormatName(dstFormat)).next();
ImageWriteParam params = writer.getDefaultWriteParam();
params.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
params.setCompressionQuality(1);
writer.setOutput(new FileImageOutputStream(destFile));
writer.write(null, new IIOImage(image, null, null), params);
} catch (IOException e) {
throw new ImageEncoderException(e);
}
}Example 37
| Project: lapdftext-master File: JPedalPDFRenderer.java View source code |
//
// Not sure if this works. Seems to be a PNG -> JPG converter.
//
private void writeImage(File outputFile, BufferedImage img) throws FileNotFoundException, IOException {
Iterator<ImageWriter> it = ImageIO.getImageWritersByFormatName("jpeg");
ImageWriter iw = it.next();
ImageWriteParam iwp = iw.getDefaultWriteParam();
iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
iwp.setCompressionQuality(1);
FileImageOutputStream outs = new FileImageOutputStream(outputFile);
iw.setOutput(outs);
IIOImage ioimage = new IIOImage(img, null, null);
iw.write(null, ioimage, iwp);
iw.dispose();
}Example 38
| Project: openmap-master File: JPEGHelper.java View source code |
private static void encodeAndWriteJPEGFile(File file, BufferedImage image, float quality) throws IOException {
Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName("jpeg");
ImageWriter writer = iter.next();
ImageWriteParam iwp = writer.getDefaultWriteParam();
iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
iwp.setCompressionQuality(quality);
FileImageOutputStream output = new FileImageOutputStream(file);
writer.setOutput(output);
IIOImage iioi = new IIOImage(image, null, null);
writer.write(null, iioi, iwp);
writer.dispose();
}Example 39
| Project: triple-master File: ImageShrinker.java View source code |
public static void main(final String[] args) throws Exception {
handleCommandLineArgs(args);
JOptionPane.showMessageDialog(null, new JLabel("<html>" + "This is the ImageShrinker, it will create a smallMap.jpeg file for you. " + "<br>Put in your base map or relief map, and it will spit out a small scaled copy of it." + "<br>Please note that the quality of the image will be worse than if you use a real painting program." + "<br>So we suggest you instead shrink the image with paint.net or photoshop or gimp, etc, then clean it " + "up before saving." + "</html>"));
final File mapFile = new FileOpen("Select The Large Image", s_mapFolderLocation, ".gif", ".png").getFile();
if (mapFile == null || !mapFile.exists()) {
throw new IllegalStateException(mapFile + "File does not exist");
}
if (s_mapFolderLocation == null) {
s_mapFolderLocation = mapFile.getParentFile();
}
final String input = JOptionPane.showInputDialog(null, "Select scale");
final float scale = Float.parseFloat(input);
final Image baseImg = ImageIO.read(mapFile);
final int thumbWidth = (int) (baseImg.getWidth(null) * scale);
final int thumbHeight = (int) (baseImg.getHeight(null) * scale);
// based on code from
// http://www.geocities.com/marcoschmidt.geo/java-save-jpeg-thumbnail.html
// draw original image to thumbnail image object and
// scale it to the new size on-the-fly
final BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB);
final Graphics2D graphics2D = thumbImage.createGraphics();
graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
graphics2D.drawImage(baseImg, 0, 0, thumbWidth, thumbHeight, null);
// save thumbnail image to OUTFILE
final File file = new File(new File(mapFile.getPath()).getParent() + File.separatorChar + "smallMap.jpeg");
final FileImageOutputStream out = new FileImageOutputStream(file);
final ImageWriter encoder = ImageIO.getImageWritersByFormatName("JPEG").next();
final JPEGImageWriteParam param = new JPEGImageWriteParam(null);
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
param.setCompressionQuality((float) 1.0);
encoder.setOutput(out);
encoder.write(null, new IIOImage(thumbImage, null, null), param);
out.close();
System.out.println("Image successfully written to " + file.getPath());
System.exit(0);
}Example 40
| Project: aranea-master File: ImageUtils.java View source code |
private void saveImage(BufferedImage image, File file) throws IOException {
Iterator iter = ImageIO.getImageWritersByFormatName("jpeg");
ImageWriter writer = (ImageWriter) iter.next();
ImageWriteParam iwp = writer.getDefaultWriteParam();
iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
iwp.setCompressionQuality(jpegCompression);
FileImageOutputStream output = new FileImageOutputStream(file);
writer.setOutput(output);
IIOImage outimage = new IIOImage(image, null, null);
writer.write(null, outimage, iwp);
writer.dispose();
}Example 41
| Project: bc-commons-master File: FileUtils.java View source code |
public static void copy(File source, File target) throws IOException {
final byte[] buffer = new byte[ONE_KB * ONE_KB];
int bytesRead;
FileImageInputStream sourceStream = null;
FileImageOutputStream targetStream = null;
try {
final File targetDir = target.getParentFile();
if (!targetDir.isDirectory()) {
if (!targetDir.mkdirs()) {
throw new IOException("failed to create target directory: " + targetDir.getAbsolutePath());
}
}
target.createNewFile();
sourceStream = new FileImageInputStream(source);
targetStream = new FileImageOutputStream(target);
while ((bytesRead = sourceStream.read(buffer)) >= 0) {
targetStream.write(buffer, 0, bytesRead);
}
} finally {
if (sourceStream != null) {
sourceStream.close();
}
if (targetStream != null) {
targetStream.flush();
targetStream.close();
}
}
}Example 42
| Project: Denizen-For-Bukkit-master File: DenizenMapManager.java View source code |
private static String downloadImage(URL url) {
try {
if (!imageDownloads.exists()) {
imageDownloads.mkdirs();
}
String urlString = CoreUtilities.toLowerCase(url.toString());
if (downloadedByUrl.containsKey(urlString)) {
File image = new File(imageDownloads, downloadedByUrl.get(urlString));
if (image.exists()) {
return image.getPath();
}
}
URLConnection connection = url.openConnection();
BufferedInputStream in = new BufferedInputStream(connection.getInputStream());
int lastDot = urlString.lastIndexOf('.');
String fileName = String.format("%0" + (6 - String.valueOf(downloadCount).length()) + "d", downloadCount) + (lastDot > 0 ? urlString.substring(lastDot) : "");
File output = new File(imageDownloads, fileName);
FileImageOutputStream out = new FileImageOutputStream(output);
int i;
while ((i = in.read()) != -1) {
out.write(i);
}
out.flush();
out.close();
in.close();
downloadedByUrl.put(urlString, fileName);
downloadCount++;
return output.getPath();
} catch (IOException e) {
dB.echoError(e);
}
return null;
}Example 43
| Project: lcm-master File: Chart2DActionSaveImageSingleton.java View source code |
/**
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
public void actionPerformed(final ActionEvent e) {
// Immediately get the image:
BufferedImage img = this.m_chart.snapShot();
// clear file filters (uncool API)
FileFilter[] farr = this.m_filechooser.getChoosableFileFilters();
for (int i = 0; i < farr.length; i++) {
this.m_filechooser.removeChoosableFileFilter(farr[i]);
}
// collect capable writers by format name (API even gets worse!)
String[] encodings = ImageIO.getWriterFormatNames();
Set<String> writers = new TreeSet<String>();
ImageTypeSpecifier spec = ImageTypeSpecifier.createFromRenderedImage(img);
Iterator<ImageWriter> itWriters;
for (int i = 0; i < encodings.length; i++) {
itWriters = ImageIO.getImageWriters(spec, encodings[i]);
if (itWriters.hasNext()) {
writers.add(encodings[i].toLowerCase());
}
}
// add the file filters:
Iterator<String> itWriterFormats = writers.iterator();
String extension;
while (itWriterFormats.hasNext()) {
extension = itWriterFormats.next();
this.m_filechooser.addChoosableFileFilter(new FileFilterExtensions(new String[] { extension }));
}
int ret = this.m_filechooser.showSaveDialog(this.m_chart);
if (ret == JFileChooser.APPROVE_OPTION) {
File file = this.m_filechooser.getSelectedFile();
// get the encoding
extension = this.m_filechooser.getFileFilter().getDescription().substring(2);
ImageWriter imgWriter = ImageIO.getImageWritersBySuffix(extension).next();
// parameters for the writer:
ImageWriteParam params = imgWriter.getDefaultWriteParam();
if (params.canWriteCompressed()) {
params.setCompressionMode(ImageWriteParam.MODE_DISABLED);
// params.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
// params.setCompressionQuality(1.0f);
}
try {
imgWriter.setOutput(new FileImageOutputStream(new File(file.getAbsolutePath() + "." + extension)));
imgWriter.write(img);
} catch (IOException e1) {
e1.printStackTrace();
}
}
}Example 44
| Project: owsi-core-parent-master File: ImageServiceImpl.java View source code |
private void generateThumbnailWithJava(File source, File destination, ImageThumbnailFormat thumbnailFormat) throws ImageThumbnailGenerationException {
try {
BufferedImage originalImage = ImageIO.read(source);
if (originalImage == null) {
throw new ServiceException("Image cannot be read.");
}
int type = (originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : originalImage.getType());
int originalImageWidth = originalImage.getWidth();
int originalImageHeight = originalImage.getHeight();
double widthRatio = (double) thumbnailFormat.getWidth() / (double) originalImageWidth;
double heightRatio = (double) thumbnailFormat.getHeight() / (double) originalImageHeight;
if (widthRatio < 1.0d || heightRatio < 1.0d) {
double ratio = Math.min(widthRatio, heightRatio);
int resizedImageWidth = (int) (ratio * originalImageWidth);
int resizedImageHeight = (int) (ratio * originalImageHeight);
BufferedImage resizedImage = new BufferedImage(resizedImageWidth, resizedImageHeight, type);
Graphics2D g = resizedImage.createGraphics();
g.setComposite(AlphaComposite.Src);
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
AffineTransform tx = new AffineTransform();
tx.scale(ratio, ratio);
g.drawImage(originalImage, 0, 0, resizedImageWidth, resizedImageHeight, null);
g.dispose();
FileImageOutputStream outputStream = null;
try {
Iterator<ImageWriter> imageWritersIterator = ImageIO.getImageWritersByFormatName(thumbnailFormat.getJavaFormatName(FilenameUtils.getExtension(destination.getName()).toLowerCase(Locale.ROOT)));
ImageWriter writer = imageWritersIterator.next();
ImageWriteParam iwp = writer.getDefaultWriteParam();
if (iwp.canWriteCompressed()) {
iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
iwp.setCompressionQuality(thumbnailFormat.getQuality() / 100f);
}
outputStream = new FileImageOutputStream(destination);
writer.setOutput(outputStream);
IIOImage image = new IIOImage(resizedImage, null, null);
writer.write(null, image, iwp);
writer.dispose();
} catch (RuntimeExceptionIOException | e) {
throw new ServiceException(e);
} finally {
if (outputStream != null) {
outputStream.close();
}
}
} else {
FileUtils.copyFile(source, destination);
}
} catch (RuntimeExceptionIOException | ServiceException | e) {
throw new ImageThumbnailGenerationException(String.format("Unable to generate a thumbnail for file %1$s", source.getAbsolutePath()), e);
}
}Example 45
| Project: picstory-master File: StoryHandler.java View source code |
private File getPicFile(String storyName, Pic pic, Size size) throws InternalException {
// Look for file in cache folder
File cache = new File(new File(cacheRoot, storyName), pic.getFilename() + "." + pic.getHash() + "." + size.toString().toLowerCase() + ".jpg");
synchronized (pic) {
if (!cache.exists()) {
try {
resizeSemaphore.acquire();
// Original file
File original = new File(new File(storyRoot, storyName), pic.getFilename() + ".jpg");
BufferedImage image = ImageIO.read(original);
// Calculate new size
int restrictWidth1 = image.getWidth(), restrictHeight1 = image.getHeight();
if (image.getWidth() > size.getMaxWidth()) {
restrictHeight1 = (int) Math.round((double) size.getMaxWidth() / (double) image.getWidth() * image.getHeight());
restrictWidth1 = size.getMaxWidth();
}
int restrictWidth2 = image.getWidth(), restrictHeight2 = image.getHeight();
if (image.getHeight() > size.getMaxHeight()) {
restrictWidth2 = (int) Math.round((double) size.getMaxHeight() / (double) image.getHeight() * image.getWidth());
restrictHeight2 = size.getMaxHeight();
}
int newWidth = Math.min(restrictWidth1, restrictWidth2);
int newHeight = Math.min(restrictHeight1, restrictHeight2);
// Image needs resizing
if (newWidth < image.getWidth() || newHeight < image.getHeight()) {
Image scaled = image.getScaledInstance(newWidth, newHeight, Image.SCALE_AREA_AVERAGING);
image = null;
image = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
image.getGraphics().drawImage(scaled, 0, 0, null);
}
// Create directory if required
File parent = cache.getParentFile();
if (!parent.exists()) {
if (!parent.mkdir()) {
throw new InternalException("Error creating folder");
}
}
// Write file
ImageWriter jpegWriter = ImageIO.getImageWritersByFormatName("jpeg").next();
ImageWriteParam param = jpegWriter.getDefaultWriteParam();
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
param.setCompressionQuality(0.75f);
FileImageOutputStream output = new FileImageOutputStream(cache);
jpegWriter.setOutput(output);
jpegWriter.write(null, new IIOImage(image, null, null), param);
output.close();
} catch (Exception e) {
throw new InternalException("Error processing file " + cache.getName(), e);
} finally {
resizeSemaphore.release();
}
}
}
return cache;
}Example 46
| Project: s1tbx-master File: GenericBSQWriter.java View source code |
/**
* Writes the in-memory representation of a data product. This method was called by <code>writeProductNodes(product,
* output)</code> of the AbstractProductWriter.
*
* @throws IllegalArgumentException if <code>output</code> type is not one of the supported output sources.
* @throws java.io.IOException if an I/O error occurs
*/
@Override
protected void writeProductNodesImpl() throws IOException {
// _outputStream = null;
final File file;
if (getOutput() instanceof String) {
file = new File((String) getOutput());
} else {
file = (File) getOutput();
}
_outputStream = new FileImageOutputStream(file);
// Default to nativeOrder
_outputStream.setByteOrder(ByteOrder.nativeOrder());
final MetadataElement absRoot = AbstractMetadata.getAbstractedMetadata(getSourceProduct());
AbstractMetadataIO.saveExternalMetadata(getSourceProduct(), absRoot, file);
// Get number of Real (not Virtual) bands
final int numOfBands = getSourceProduct().getNumBands();
for (int i = 0; i < numOfBands; i++) {
if (!(getSourceProduct().getBandAt(i) instanceof VirtualBand)) {
numOfWriteBands++;
}
}
}Example 47
| Project: sejda-master File: PageImageWriter.java View source code |
public static String convertImageTo(String filePath, String format) throws IOException, TaskIOException {
BufferedImage image = ImageIO.read(new File(filePath));
File tmpFile = IOUtils.createTemporaryBuffer("." + format);
ImageOutputStream outputStream = new FileImageOutputStream(tmpFile);
try {
ImageWriter writer = ImageIO.getImageWritersByFormatName(format).next();
writer.setOutput(outputStream);
ImageWriteParam param = writer.getDefaultWriteParam();
if (format.equals("jpeg")) {
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
param.setCompressionQuality(1.0F);
}
writer.write(null, new IIOImage(image, null, null), param);
} finally {
org.apache.commons.io.IOUtils.closeQuietly(outputStream);
}
return tmpFile.getPath();
}Example 48
| Project: Advanced-Logon-Editor-master File: FileUtil.java View source code |
/**
* Scales image to 256kb
*
* @param img Imagepath
* @throws IOException -
*/
public static void scaleImageTo256kb(Path img) throws IOException {
File imgFile = img.toFile();
if (imgFile.length() <= BYTE) {
return;
}
File newFile = Constants.PROGRAM_TMP_PATH.resolve(img.getFileName()).toFile();
BufferedImage i = ImageIO.read(imgFile);
if (i.getWidth() > MAXWIDTH) {
BufferedImage j = new BufferedImage(MAXWIDTH, (int) (i.getHeight() * ((float) MAXWIDTH / i.getWidth())), i.getType());
Graphics2D g2 = (Graphics2D) j.getGraphics();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
g2.drawImage(i, 0, 0, j.getWidth(), j.getHeight(), null);
ImageIO.write(j, "jpg", imgFile);
}
float quality = 1f;
float eps = 0.2f;
int c = 0;
Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName("jpeg");
ImageWriter writer = iter.next();
ImageWriteParam iwp = writer.getDefaultWriteParam();
iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
FileImageOutputStream output;
IIOImage image;
do {
c++;
FileUtil.deleteFile(newFile.toPath());
iwp.setCompressionQuality(quality);
output = new FileImageOutputStream(newFile);
writer.setOutput(output);
image = new IIOImage(ImageIO.read(imgFile), null, null);
writer.write(null, image, iwp);
writer.reset();
output.flush();
output.close();
quality -= eps / c;
} while ((newFile.length() > BYTE) && (quality > 0.1));
FileUtil.deleteFile(img);
FileUtil.moveFile(newFile.toPath(), img);
}Example 49
| Project: h2-bitmap-master File: TestMVRTree.java View source code |
private static void render(MVRTreeMap<SpatialKey, String> r, String fileName) {
int width = 1000, height = 500;
BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = (Graphics2D) img.getGraphics();
g2d.setBackground(Color.WHITE);
g2d.setColor(Color.WHITE);
g2d.fillRect(0, 0, width, height);
g2d.setComposite(AlphaComposite.SrcOver.derive(0.5f));
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(Color.BLACK);
SpatialKey b = new SpatialKey(0, Float.MAX_VALUE, Float.MIN_VALUE, Float.MAX_VALUE, Float.MIN_VALUE);
for (SpatialKey x : r.keySet()) {
b.setMin(0, Math.min(b.min(0), x.min(0)));
b.setMin(1, Math.min(b.min(1), x.min(1)));
b.setMax(0, Math.max(b.max(0), x.max(0)));
b.setMax(1, Math.max(b.max(1), x.max(1)));
}
// System.out.println(b);
for (SpatialKey x : r.keySet()) {
int[] rect = scale(b, x, width, height);
g2d.drawRect(rect[0], rect[1], rect[2] - rect[0], rect[3] - rect[1]);
String s = r.get(x);
g2d.drawChars(s.toCharArray(), 0, s.length(), rect[0], rect[1] - 4);
}
g2d.setColor(Color.red);
ArrayList<SpatialKey> list = New.arrayList();
r.addNodeKeys(list, r.getRoot());
for (SpatialKey x : list) {
int[] rect = scale(b, x, width, height);
g2d.drawRect(rect[0], rect[1], rect[2] - rect[0], rect[3] - rect[1]);
}
ImageWriter out = ImageIO.getImageWritersByFormatName("png").next();
try {
out.setOutput(new FileImageOutputStream(new File(fileName)));
out.write(img);
} catch (IOException e) {
throw new RuntimeException(e);
}
}Example 50
| Project: mapfish-print-master File: ImageSimilarity.java View source code |
/**
* Write the image to a file in uncompressed tiff format.
*
* @param image image to write
* @param file path and file name (extension will be ignored and changed to tiff.
*/
public static void writeUncompressedImage(BufferedImage image, String file) throws IOException {
FileImageOutputStream out = null;
try {
final File parentFile = new File(file).getParentFile();
Iterator<ImageWriter> writers = ImageIO.getImageWritersBySuffix("tiff");
final ImageWriter next = writers.next();
final ImageWriteParam param = next.getDefaultWriteParam();
param.setCompressionMode(ImageWriteParam.MODE_DISABLED);
final File outputFile = new File(parentFile, Files.getNameWithoutExtension(file) + ".tiff");
out = new FileImageOutputStream(outputFile);
next.setOutput(out);
next.write(image);
} catch (Throwable e) {
System.err.println(String.format("Error writing the image generated by the test: %s%n\t", file));
e.printStackTrace();
} finally {
if (out != null) {
out.close();
}
}
}Example 51
| Project: RestComm-master File: Images.java View source code |
/**
* Resize an image
* @param originalImage The image file
* @param to The destination file
* @param w The new width (or -1 to proportionally resize) or the maxWidth if keepRatio is true
* @param h The new height (or -1 to proportionally resize) or the maxHeight if keepRatio is true
* @param keepRatio : if true, resize will keep the original image ratio and use w and h as max dimensions
*/
public static void resize(File originalImage, File to, int w, int h, boolean keepRatio) {
try {
BufferedImage source = ImageIO.read(originalImage);
int owidth = source.getWidth();
int oheight = source.getHeight();
double ratio = (double) owidth / oheight;
int maxWidth = w;
int maxHeight = h;
if (w < 0 && h < 0) {
w = owidth;
h = oheight;
}
if (w < 0 && h > 0) {
w = (int) (h * ratio);
}
if (w > 0 && h < 0) {
h = (int) (w / ratio);
}
if (keepRatio) {
h = (int) (w / ratio);
if (h > maxHeight) {
h = maxHeight;
w = (int) (h * ratio);
}
if (w > maxWidth) {
w = maxWidth;
h = (int) (w / ratio);
}
}
String mimeType = "image/jpeg";
if (to.getName().endsWith(".png")) {
mimeType = "image/png";
}
if (to.getName().endsWith(".gif")) {
mimeType = "image/gif";
}
// out
BufferedImage dest = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Image srcSized = source.getScaledInstance(w, h, Image.SCALE_SMOOTH);
Graphics graphics = dest.getGraphics();
graphics.setColor(Color.WHITE);
graphics.fillRect(0, 0, w, h);
graphics.drawImage(srcSized, 0, 0, null);
ImageWriter writer = ImageIO.getImageWritersByMIMEType(mimeType).next();
ImageWriteParam params = writer.getDefaultWriteParam();
FileImageOutputStream toFs = new FileImageOutputStream(to);
writer.setOutput(toFs);
IIOImage image = new IIOImage(dest, null, null);
writer.write(null, image, params);
toFs.flush();
toFs.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}Example 52
| Project: restcommander-master File: Images.java View source code |
/**
* Resize an image
* @param originalImage The image file
* @param to The destination file
* @param w The new width (or -1 to proportionally resize) or the maxWidth if keepRatio is true
* @param h The new height (or -1 to proportionally resize) or the maxHeight if keepRatio is true
* @param keepRatio : if true, resize will keep the original image ratio and use w and h as max dimensions
*/
public static void resize(File originalImage, File to, int w, int h, boolean keepRatio) {
try {
BufferedImage source = ImageIO.read(originalImage);
int owidth = source.getWidth();
int oheight = source.getHeight();
double ratio = (double) owidth / oheight;
int maxWidth = w;
int maxHeight = h;
if (w < 0 && h < 0) {
w = owidth;
h = oheight;
}
if (w < 0 && h > 0) {
w = (int) (h * ratio);
}
if (w > 0 && h < 0) {
h = (int) (w / ratio);
}
if (keepRatio) {
h = (int) (w / ratio);
if (h > maxHeight) {
h = maxHeight;
w = (int) (h * ratio);
}
if (w > maxWidth) {
w = maxWidth;
h = (int) (w / ratio);
}
}
String mimeType = "image/jpeg";
if (to.getName().endsWith(".png")) {
mimeType = "image/png";
}
if (to.getName().endsWith(".gif")) {
mimeType = "image/gif";
}
// out
BufferedImage dest = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Image srcSized = source.getScaledInstance(w, h, Image.SCALE_SMOOTH);
Graphics graphics = dest.getGraphics();
graphics.setColor(Color.WHITE);
graphics.fillRect(0, 0, w, h);
graphics.drawImage(srcSized, 0, 0, null);
ImageWriter writer = ImageIO.getImageWritersByMIMEType(mimeType).next();
ImageWriteParam params = writer.getDefaultWriteParam();
FileImageOutputStream toFs = new FileImageOutputStream(to);
writer.setOutput(toFs);
IIOImage image = new IIOImage(dest, null, null);
writer.write(null, image, params);
toFs.flush();
toFs.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}Example 53
| Project: XChart-master File: BitmapEncoder.java View source code |
/**
* Save a chart as a PNG with a custom DPI. The default DPI is 72, which is fine for displaying charts on a computer monitor, but for printing
* charts, a DPI of around 300 is much better.
*
* @param chart
* @param fileName
* @param DPI
* @throws IOException
*/
public static void saveBitmapWithDPI(Chart chart, String fileName, BitmapFormat bitmapFormat, int DPI) throws IOException {
double scaleFactor = DPI / 72.0;
BufferedImage bufferedImage = new BufferedImage((int) (chart.getWidth() * scaleFactor), (int) (chart.getHeight() * scaleFactor), BufferedImage.TYPE_INT_RGB);
Graphics2D graphics2D = bufferedImage.createGraphics();
AffineTransform at = graphics2D.getTransform();
at.scale(scaleFactor, scaleFactor);
graphics2D.setTransform(at);
chart.paint(graphics2D, chart.getWidth(), chart.getHeight());
Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName(bitmapFormat.toString().toLowerCase());
if (writers.hasNext()) {
ImageWriter writer = writers.next();
// instantiate an ImageWriteParam object with default compression options
ImageWriteParam iwp = writer.getDefaultWriteParam();
ImageTypeSpecifier typeSpecifier = ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_INT_RGB);
IIOMetadata metadata = writer.getDefaultImageMetadata(typeSpecifier, iwp);
if (metadata.isReadOnly() || !metadata.isStandardMetadataFormatSupported()) {
throw new IllegalArgumentException("It is not possible to set the DPI on a bitmap with " + bitmapFormat + " format!! Try another format.");
}
setDPI(metadata, DPI);
File file = new File(addFileExtension(fileName, bitmapFormat));
FileImageOutputStream output = new FileImageOutputStream(file);
writer.setOutput(output);
IIOImage image = new IIOImage(bufferedImage, null, metadata);
try {
writer.write(null, image, iwp);
writer.dispose();
} finally {
output.close();
}
}
}Example 54
| Project: bricket-master File: PictureModificationServiceImpl.java View source code |
private void writeJpeg(BufferedImage image, File file, float quality) throws IOException {
ImageWriter writer = ImageIO.getImageWritersByFormatName("jpeg").next();
ImageWriteParam iwp = writer.getDefaultWriteParam();
iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
iwp.setCompressionQuality(quality);
FileImageOutputStream output = new FileImageOutputStream(file);
writer.setOutput(output);
writer.write(null, new IIOImage(image, null, null), iwp);
}Example 55
| Project: H2-Mirror-master File: TestMVRTree.java View source code |
private static void render(MVRTreeMap<String> r, String fileName) {
int width = 1000, height = 500;
BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = (Graphics2D) img.getGraphics();
g2d.setBackground(Color.WHITE);
g2d.setColor(Color.WHITE);
g2d.fillRect(0, 0, width, height);
g2d.setComposite(AlphaComposite.SrcOver.derive(0.5f));
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(Color.BLACK);
SpatialKey b = new SpatialKey(0, Float.MAX_VALUE, Float.MIN_VALUE, Float.MAX_VALUE, Float.MIN_VALUE);
for (SpatialKey x : r.keySet()) {
b.setMin(0, Math.min(b.min(0), x.min(0)));
b.setMin(1, Math.min(b.min(1), x.min(1)));
b.setMax(0, Math.max(b.max(0), x.max(0)));
b.setMax(1, Math.max(b.max(1), x.max(1)));
}
// System.out.println(b);
for (SpatialKey x : r.keySet()) {
int[] rect = scale(b, x, width, height);
g2d.drawRect(rect[0], rect[1], rect[2] - rect[0], rect[3] - rect[1]);
String s = r.get(x);
g2d.drawChars(s.toCharArray(), 0, s.length(), rect[0], rect[1] - 4);
}
g2d.setColor(Color.red);
ArrayList<SpatialKey> list = New.arrayList();
r.addNodeKeys(list, r.getRoot());
for (SpatialKey x : list) {
int[] rect = scale(b, x, width, height);
g2d.drawRect(rect[0], rect[1], rect[2] - rect[0], rect[3] - rect[1]);
}
ImageWriter out = ImageIO.getImageWritersByFormatName("png").next();
try {
out.setOutput(new FileImageOutputStream(new File(fileName)));
out.write(img);
} catch (IOException e) {
throw new RuntimeException(e);
}
}Example 56
| Project: H2-Research-master File: TestMVRTree.java View source code |
private static void render(MVRTreeMap<String> r, String fileName) {
int width = 1000, height = 500;
BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = (Graphics2D) img.getGraphics();
g2d.setBackground(Color.WHITE);
g2d.setColor(Color.WHITE);
g2d.fillRect(0, 0, width, height);
g2d.setComposite(AlphaComposite.SrcOver.derive(0.5f));
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(Color.BLACK);
SpatialKey b = new SpatialKey(0, Float.MAX_VALUE, Float.MIN_VALUE, Float.MAX_VALUE, Float.MIN_VALUE);
for (SpatialKey x : r.keySet()) {
b.setMin(0, Math.min(b.min(0), x.min(0)));
b.setMin(1, Math.min(b.min(1), x.min(1)));
b.setMax(0, Math.max(b.max(0), x.max(0)));
b.setMax(1, Math.max(b.max(1), x.max(1)));
}
// System.out.println(b);
for (SpatialKey x : r.keySet()) {
int[] rect = scale(b, x, width, height);
g2d.drawRect(rect[0], rect[1], rect[2] - rect[0], rect[3] - rect[1]);
String s = r.get(x);
g2d.drawChars(s.toCharArray(), 0, s.length(), rect[0], rect[1] - 4);
}
g2d.setColor(Color.red);
ArrayList<SpatialKey> list = New.arrayList();
r.addNodeKeys(list, r.getRoot());
for (SpatialKey x : list) {
int[] rect = scale(b, x, width, height);
g2d.drawRect(rect[0], rect[1], rect[2] - rect[0], rect[3] - rect[1]);
}
ImageWriter out = ImageIO.getImageWritersByFormatName("png").next();
try {
out.setOutput(new FileImageOutputStream(new File(fileName)));
out.write(img);
} catch (IOException e) {
throw new RuntimeException(e);
}
}Example 57
| Project: h2database-master File: TestMVRTree.java View source code |
private static void render(MVRTreeMap<String> r, String fileName) {
int width = 1000, height = 500;
BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = (Graphics2D) img.getGraphics();
g2d.setBackground(Color.WHITE);
g2d.setColor(Color.WHITE);
g2d.fillRect(0, 0, width, height);
g2d.setComposite(AlphaComposite.SrcOver.derive(0.5f));
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(Color.BLACK);
SpatialKey b = new SpatialKey(0, Float.MAX_VALUE, Float.MIN_VALUE, Float.MAX_VALUE, Float.MIN_VALUE);
for (SpatialKey x : r.keySet()) {
b.setMin(0, Math.min(b.min(0), x.min(0)));
b.setMin(1, Math.min(b.min(1), x.min(1)));
b.setMax(0, Math.max(b.max(0), x.max(0)));
b.setMax(1, Math.max(b.max(1), x.max(1)));
}
// System.out.println(b);
for (SpatialKey x : r.keySet()) {
int[] rect = scale(b, x, width, height);
g2d.drawRect(rect[0], rect[1], rect[2] - rect[0], rect[3] - rect[1]);
String s = r.get(x);
g2d.drawChars(s.toCharArray(), 0, s.length(), rect[0], rect[1] - 4);
}
g2d.setColor(Color.red);
ArrayList<SpatialKey> list = New.arrayList();
r.addNodeKeys(list, r.getRoot());
for (SpatialKey x : list) {
int[] rect = scale(b, x, width, height);
g2d.drawRect(rect[0], rect[1], rect[2] - rect[0], rect[3] - rect[1]);
}
ImageWriter out = ImageIO.getImageWritersByFormatName("png").next();
try {
out.setOutput(new FileImageOutputStream(new File(fileName)));
out.write(img);
} catch (IOException e) {
throw new RuntimeException(e);
}
}Example 58
| Project: jupload-master File: ImageReaderWriterHelper.java View source code |
// ////////////////////////////////////////////////////////////////////
// //////////////////// PUBLIC METHODS
// ////////////////////////////////////////////////////////////////////
/**
* Creates a FileImageOutputStream, and assign it as the output to the
* imageWriter.
*
* @param file The file where the output stream must write.
* @throws JUploadIOException Any error...
*/
public void setOutput(File file) throws JUploadIOException {
// We first initialize internal variable.
initImageWriter();
try {
fileImageOutputStream = new FileImageOutputStream(file);
} catch (IOException e) {
throw new JUploadIOException("ImageReaderWriterHelper.setOutput()", e);
}
imageWriter.setOutput(fileImageOutputStream);
}Example 59
| Project: statalign-master File: VueUI.java View source code |
public void saveToJPEG(String filename) throws ExceptionJPEGEncoding, ExceptionExportFailed {
VueJPEG jpeg = new VueJPEG(true, true);
if (JOptionPane.showConfirmDialog(_vp, jpeg.getPanel(), "Set resolution/quality", JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION) {
Double scale;
if (jpeg.getScaleSlider().getValue() == 0)
scale = 1. / 100.;
else
scale = jpeg.getScaleSlider().getValue() / 100.;
BufferedImage myImage = new BufferedImage((int) Math.round(_vp.getWidth() * scale), (int) Math.round(_vp.getHeight() * scale), BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = myImage.createGraphics();
AffineTransform AF = new AffineTransform();
AF.setToScale(scale, scale);
g2.setTransform(AF);
_vp.paintComponent(g2);
try {
FileImageOutputStream out = new FileImageOutputStream(new File(filename));
ImageWriter writer = ImageIO.getImageWritersByFormatName("jpeg").next();
ImageWriteParam params = writer.getDefaultWriteParam();
params.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
params.setCompressionQuality(jpeg.getQualitySlider().getValue() / 100.0f);
writer.setOutput(out);
IIOImage myIIOImage = new IIOImage(myImage, null, null);
writer.write(null, myIIOImage, params);
out.close();
} catch (IOException e) {
throw new ExceptionExportFailed(e.getMessage(), filename);
}
}
}Example 60
| Project: Triana-master File: ImageAction.java View source code |
private static void save(File f, Component comp, double scale, Rectangle2D rect, BufferedImage image, String type, boolean display) {
if (scale == 0.0) {
scale = 0.1;
}
String nm = f.getName();
if (nm.indexOf(".") > -1) {
nm = nm.substring(0, nm.indexOf(".") + 1) + type;
} else {
nm += ("." + type);
}
File out = new File(f.getParentFile(), nm);
if (out.exists()) {
int choice = JOptionPane.OK_OPTION;
if (display) {
choice = JOptionPane.showConfirmDialog(GUIEnv.getApplicationFrame(), "Over write existing file '" + nm + "'?", "Over Write", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, GUIEnv.getTrianaIcon());
}
if (choice == JOptionPane.CANCEL_OPTION) {
return;
} else {
String path = out.getAbsolutePath();
out.delete();
out = new File(path);
}
}
comp.paint(image.getGraphics());
AffineTransform tx = new AffineTransform();
tx.scale(scale, scale);
tx.translate(-(rect.getX() - (margin)), -(rect.getY() - (margin)));
AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_BILINEAR);
BufferedImage dest = new BufferedImage((int) ((rect.getWidth()) * scale) + (margin * 2), (int) ((rect.getHeight()) * scale) + (margin * 2), BufferedImage.TYPE_INT_RGB);
Graphics g = dest.getGraphics();
Color c = g.getColor();
g.setColor(comp.getBackground());
g.fillRect(0, 0, dest.getWidth(), dest.getHeight());
g.setColor(c);
image = op.filter(image, dest);
Iterator iter = ImageIO.getImageWritersByFormatName(type);
if (iter == null || !iter.hasNext()) {
if (display) {
OptionPane.showError("No Image writers availabale for " + type, "Error", GUIEnv.getApplicationFrame());
} else {
System.out.println("ImageAction.save: No Image writers could be found for:" + type);
}
}
ImageWriter writer = (ImageWriter) iter.next();
ImageWriteParam iwp = writer.getDefaultWriteParam();
if (writer.canWriteRasters()) {
iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
iwp.setCompressionQuality(1);
}
try {
FileImageOutputStream fout = new FileImageOutputStream(out);
writer.setOutput(fout);
IIOImage im = new IIOImage(image, null, null);
writer.write(null, im, iwp);
writer.dispose();
fout.flush();
fout.close();
} catch (IOException e) {
if (display) {
OptionPane.showError(e.getMessage(), "Error", GUIEnv.getApplicationFrame());
} else {
e.printStackTrace();
}
}
}Example 61
| Project: emul-master File: ConvertImages.java View source code |
/**
* @param datas
* @param out
* @throws IOException
*/
private void saveImage(ImageImportData[] datas, File outBase) throws IOException {
if (showPalette) {
for (ImageImportData data : datas) {
byte[][] palette = data.getThePalette();
System.out.println("Palette:\n" + dumpPalette(palette));
BufferedImage palImg = new BufferedImage(palette.length, 1, BufferedImage.TYPE_3BYTE_BGR);
for (int i = 0; i < palImg.getWidth(); i++) {
int rgb = (palette[i][2] & 0xff) | ((palette[i][1] << 8) & 0xff00) | ((palette[i][0] << 16) & 0xff0000);
palImg.setRGB(i, 0, rgb);
}
String out = outBase.getPath() + "_pal.png";
ImageIO.write(palImg, "png", new File(out));
String[] args = { "/usr/bin/display", "-sample", "1600%x1600%", out };
Runtime.getRuntime().exec(args);
}
}
if (datas.length == 1) {
BufferedImage cvt = datas[0].getConvertedImage();
if (opts.getPaletteUsage() == PaletteOption.OPTIMIZED) {
// flatten pixels, to account for loss of palette precision
int w = cvt.getWidth();
int h = cvt.getHeight();
int[] rgb = { 0, 0, 0 };
int[] rgbs = new int[w];
for (int y = 0; y < h; y++) {
cvt.getRGB(0, y, w, 1, rgbs, 0, w);
for (int x = 0; x < w; x++) {
rgb[0] = (rgbs[x] & 0xff0000) >> 16;
rgb[1] = (rgbs[x] & 0xff00) >> 8;
rgb[2] = (rgbs[x] & 0xff);
rgb[0] = (rgb[0] * 0xff / 0xdf);
rgb[1] = (rgb[1] * 0xff / 0xdf);
rgb[2] = (rgb[2] * 0xff / 0xdf);
rgbs[x] = (Math.min(255, rgb[0]) << 16) | (Math.min(255, rgb[1]) << 8) | Math.min(255, rgb[2]);
}
//converted.setRGB(0, y, w, 1, rgbs, 0, w);
}
}
cvt = stretchImage(cvt);
String out = outBase.getPath() + ".png";
ImageIO.write(cvt, "png", new File(out));
String[] args = { "/usr/bin/display", "-sample", "200%x200%", out };
if (width >= 512) {
args[2] = "100%x100%";
} else if (opts.getFormat() == VdpFormat.COLOR16_4x4 || width <= 64 || height <= 48) {
args[2] = "800%x800%";
} else if (width <= 128 || height <= 96) {
args[2] = "400%x400%";
}
Runtime.getRuntime().exec(args);
return;
}
// animated GIF?
String out = outBase.getPath() + ".gif";
ImageOutputStream outs = new FileImageOutputStream(new File(out));
GifSequenceWriter writer = new GifSequenceWriter(outs, datas[0].getConvertedImage().getType(), datas[0].delayMs, true);
for (int i = 0; i < datas.length; i++) {
BufferedImage frame = stretchImage(datas[i].getConvertedImage());
writer.writeToSequence(frame);
}
writer.close();
outs.close();
String[] args = { "/usr/bin/eog", out };
Runtime.getRuntime().exec(args);
}Example 62
| Project: jgrasstools-master File: ExifGpsWriter.java View source code |
/**
* Main method to write the gps data to the exif
* @param gps - gps position to be added
* @throws IOException
*/
private void writeExif() throws IOException {
IIOMetadata metadata = jpegReader.getImageMetadata(0);
// names says which exif tree to get - 0 for jpeg 1 for the default
String[] names = metadata.getMetadataFormatNames();
IIOMetadataNode root = (IIOMetadataNode) metadata.getAsTree(names[0]);
// exif is on the app1 node called unknown
NodeList nList = root.getElementsByTagName("unknown");
IIOMetadataNode app1EXIFNode = (IIOMetadataNode) nList.item(0);
ArrayList<IIOMetadata> md = readExif(app1EXIFNode);
IIOMetadata exifMetadata = md.get(0);
// insert the gps data into the exif
exifMetadata = insertGPSCoords(exifMetadata);
// create a new exif node
IIOMetadataNode app1NodeNew = createNewExifNode(exifMetadata, null, null);
// copy the user data accross
app1EXIFNode.setUserObject(app1NodeNew.getUserObject());
// write to a new image file
FileImageOutputStream out1 = new FileImageOutputStream(new File("GPS_" + imageFile.getName()));
jpegWriter.setOutput(out1);
metadata.setFromTree(names[0], root);
IIOImage image = new IIOImage(jpegReader.readAsRenderedImage(0, jpegReader.getDefaultReadParam()), null, metadata);
// write out the new image
jpegWriter.write(jpegReader.getStreamMetadata(), image, jpegWriter.getDefaultWriteParam());
}Example 63
| Project: mage-master File: DownloadPictures.java View source code |
private void writeImageToFile(BufferedImage image, TFile file) throws IOException {
Iterator iter = ImageIO.getImageWritersByFormatName("jpg");
ImageWriter writer = (ImageWriter) iter.next();
ImageWriteParam iwp = writer.getDefaultWriteParam();
iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
iwp.setCompressionQuality(0.96f);
File tempFile = new File(Constants.IO.imageBaseDir + File.separator + image.hashCode() + file.getName());
FileImageOutputStream output = new FileImageOutputStream(tempFile);
writer.setOutput(output);
IIOImage image2 = new IIOImage(image, null, null);
writer.write(null, image2, iwp);
writer.dispose();
output.close();
new TFile(tempFile).cp_rp(file);
tempFile.delete();
}Example 64
| Project: openolat-master File: ImageHelperImpl.java View source code |
/**
* Can change this to choose a better compression level as the default
* @param image
* @param scaledImage
* @return
*/
public static boolean writeTo(BufferedImage image, File scaledImage, Size scaledSize, String outputFormat) {
try {
if (!StringHelper.containsNonWhitespace(outputFormat)) {
outputFormat = OUTPUT_FORMAT;
}
Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName(outputFormat);
if (writers.hasNext()) {
ImageWriter writer = writers.next();
ImageWriteParam iwp = getOptimizedImageWriteParam(writer, scaledSize);
IIOImage iiOImage = new IIOImage(image, null, null);
ImageOutputStream iOut = new FileImageOutputStream(scaledImage);
writer.setOutput(iOut);
writer.write(null, iiOImage, iwp);
writer.dispose();
iOut.flush();
iOut.close();
return true;
} else {
return ImageIO.write(image, outputFormat, scaledImage);
}
} catch (IOException e) {
return false;
}
}Example 65
| Project: Feuille-master File: WavePanel.java View source code |
// <editor-fold defaultstate="collapsed" desc="JavaSound API + JMF API methods">
private boolean writeInImageOutput(FileImageOutputStream fileIOS, BufferedImage bi, boolean andCloseIt) {
try {
//Appends new graphics to the output
ImageIO.write(bi, "PNG", fileIOS);
if (andCloseIt == false) {
fileIOS.flush();
} else {
fileIOS.close();
}
} catch (java.io.IOException ioe) {
System.out.println("PNG Aborted");
return false;
}
return true;
}Example 66
| Project: JAVMovieScraper-master File: Movie.java View source code |
public void writeToFile(File nfoFile, File posterFile, File fanartFile, File currentlySelectedFolderJpgFile, File targetFolderForExtraFanartFolderAndActorFolder, File trailerFile, MoviescraperPreferences preferences) throws IOException {
//ID only appended if preference set and not already at the start of the title
if (!title.getTitle().startsWith(id.getId())) {
appendIDToStartOfTitle();
}
String xml = new KodiXmlMovieBean(this).toXML();
// add the xml header since xstream doesn't do this
xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\" ?>" + "\n" + xml;
if (nfoFile != null && xml.length() > 0)
nfoFile.delete();
FileUtils.writeStringToFile(nfoFile, xml, org.apache.commons.lang3.CharEncoding.UTF_8);
Thumb posterToSaveToDisk = null;
if (posters != null && posters.length > 0)
posterToSaveToDisk = posters[0];
boolean writePoster = preferences.getWriteFanartAndPostersPreference();
boolean writeFanart = preferences.getWriteFanartAndPostersPreference();
boolean writePosterIfAlreadyExists = preferences.getOverWriteFanartAndPostersPreference();
boolean writeFanartIfAlreadyExists = preferences.getOverWriteFanartAndPostersPreference();
boolean createFolderJpgEnabledPreference = preferences.getCreateFolderJpgEnabledPreference();
// maybe we did some clipping, so we're going to have to reencode it
if (this.getPosters().length > 0 && (writePoster || createFolderJpgEnabledPreference) && ((posterFile.exists() == writePosterIfAlreadyExists) || (!posterFile.exists() || (createFolderJpgEnabledPreference)))) {
if (posterToSaveToDisk != null && (posterToSaveToDisk.isModified() || createFolderJpgEnabledPreference || !posterFile.exists() || writePosterIfAlreadyExists)) {
//reencode the jpg since we probably did a resize
Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName("jpeg");
ImageWriter writer = (ImageWriter) iter.next();
// instantiate an ImageWriteParam object with default compression options
ImageWriteParam iwp = writer.getDefaultWriteParam();
iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
// an float between 0 and 1
iwp.setCompressionQuality(1);
// 1 specifies minimum compression and maximum quality
IIOImage image = new IIOImage((RenderedImage) posterToSaveToDisk.getThumbImage(), null, null);
if (writePoster && posterToSaveToDisk.isModified()) {
System.out.println("Writing poster to " + posterFile);
try (FileImageOutputStream posterFileOutput = new FileImageOutputStream(posterFile)) {
writer.setOutput(posterFileOutput);
writer.write(null, image, iwp);
}
} else //write out the poster file without reencoding it and resizing it
if ((!posterFile.exists() || writePosterIfAlreadyExists) && posterToSaveToDisk.getThumbURL() != null) {
System.out.println("Writing poster file from nfo: " + posterFile);
FileDownloaderUtilities.writeURLToFile(posterToSaveToDisk.getThumbURL(), posterFile, posterToSaveToDisk.getReferrerURL());
}
if (createFolderJpgEnabledPreference && currentlySelectedFolderJpgFile != null) {
if (!posterToSaveToDisk.isModified() && (!currentlySelectedFolderJpgFile.exists() || (currentlySelectedFolderJpgFile.exists() && writePosterIfAlreadyExists))) {
System.out.println("Writing folder.jpg (no changes) to " + currentlySelectedFolderJpgFile);
FileDownloaderUtilities.writeURLToFile(posterToSaveToDisk.getThumbURL(), currentlySelectedFolderJpgFile, posterToSaveToDisk.getReferrerURL());
} else {
if (!currentlySelectedFolderJpgFile.exists() || (currentlySelectedFolderJpgFile.exists() && writePosterIfAlreadyExists)) {
System.out.println("Writing folder to " + currentlySelectedFolderJpgFile);
try (FileImageOutputStream folderFileOutput = new FileImageOutputStream(currentlySelectedFolderJpgFile)) {
writer.setOutput(folderFileOutput);
writer.write(null, image, iwp);
}
} else {
System.out.println("Skipping overwrite of folder.jpg due to preference setting");
}
}
}
writer.dispose();
}
}
// we didn't modify it so we can write it directly from the URL
if (this.getFanart().length > 0 && writeFanart && ((fanartFile.exists() == writeFanartIfAlreadyExists) || !fanartFile.exists())) {
if (fanart != null && fanart.length > 0) {
Thumb fanartToSaveToDisk;
if (preferredFanartToWriteToDisk != null)
fanartToSaveToDisk = preferredFanartToWriteToDisk;
else
fanartToSaveToDisk = fanart[0];
System.out.println("saving out first fanart to " + fanartFile);
//can save ourself redownloading the image if it's already in memory, but we dont want to reencode the image, so only do this if it's modified
if (fanartToSaveToDisk.getImageIconThumbImage() != null && fanartToSaveToDisk.isModified()) {
try {
ImageIO.write(fanartToSaveToDisk.toBufferedImage(), "jpg", fanartFile);
} catch (IOException e) {
System.err.println("Failed to write fanart due to io error");
e.printStackTrace();
}
} else
//download the url and save it out to disk
FileDownloaderUtilities.writeURLToFile(fanartToSaveToDisk.getThumbURL(), fanartFile, posterToSaveToDisk.getReferrerURL());
}
}
//write out the extrafanart, if the preference for it is set
if (targetFolderForExtraFanartFolderAndActorFolder != null && preferences.getExtraFanartScrapingEnabledPreference()) {
System.out.println("Starting write of extra fanart into " + targetFolderForExtraFanartFolderAndActorFolder);
writeExtraFanart(targetFolderForExtraFanartFolderAndActorFolder);
}
//write the .actor images, if the preference for it is set
if (preferences.getDownloadActorImagesToActorFolderPreference() && targetFolderForExtraFanartFolderAndActorFolder != null) {
System.out.println("Writing .actor images into " + targetFolderForExtraFanartFolderAndActorFolder);
writeActorImagesToFolder(targetFolderForExtraFanartFolderAndActorFolder);
}
//write out the trailer, if the preference for it is set
Trailer trailerToWrite = getTrailer();
if (preferences.getWriteTrailerToFile() && trailerToWrite != null && trailerToWrite.getTrailer().length() > 0) {
trailerToWrite.writeTrailerToFile(trailerFile);
}
}Example 67
| Project: jpexs-decompiler-master File: FrameExporter.java View source code |
public static void makeGIFOld(Iterator<BufferedImage> images, float frameRate, File file, EventListener evl) throws IOException {
if (!images.hasNext()) {
return;
}
try (ImageOutputStream output = new FileImageOutputStream(file)) {
BufferedImage img0 = images.next();
GifSequenceWriter writer = new GifSequenceWriter(output, img0.getType(), (int) (1000.0 / frameRate), true);
writer.writeToSequence(img0);
while (images.hasNext()) {
writer.writeToSequence(images.next());
}
writer.close();
}
}Example 68
| Project: LateralGM-master File: Util.java View source code |
//TODO: JPEG Writing is bugged in some newer JVM versions causing the RGB color channels to be mixed up.
// This is a bug Oracle claims to have fixed but they actually haven't.
// http://bugs.java.com/view_bug.do?bug_id=4712797
// http://bugs.java.com/view_bug.do?bug_id=4776576
// http://stackoverflow.com/questions/13072312/jpeg-image-color-gets-drastically-changed-after-just-imageio-read-and-imageio
public static void writeImageQualityPrompt(BufferedImage img, String ext, File f) throws FileNotFoundException, IOException {
Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName(ext);
ImageWriter writer = (ImageWriter) iter.next();
BMPImageWriteParam iwp = (BMPImageWriteParam) writer.getDefaultWriteParam();
if (iwp.canWriteCompressed()) {
iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
for (String str : iwp.getCompressionTypes()) {
System.out.println(str);
}
if (ext.equals("jpg") || ext.equals("jpeg")) {
iwp.setCompressionQuality(1.0f);
} else if (ext.equals("bmp")) {
iwp = (BMPImageWriteParam) iwp;
//iwp.setCompressionType("BI_BITFIELDS");
iwp.setCompressionType("BI_RLE4");
//iwp.setCompressionType("BI_RLE8");
//iwp.setCompressionType("BI_RGB");
}
}
FileImageOutputStream output = new FileImageOutputStream(f);
writer.setOutput(output);
IIOImage image = new IIOImage(img, null, null);
writer.write(null, image, iwp);
writer.dispose();
output.close();
}Example 69
| Project: sweethome3d-master File: PhotosPanel.java View source code |
/**
* Saves the given <code>image</code>.
*/
private void savePhoto(BufferedImage image, File file) throws IOException {
String fileFormat = this.controller.getFileFormat();
Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName(fileFormat);
ImageWriter writer = (ImageWriter) iter.next();
ImageWriteParam writeParam = writer.getDefaultWriteParam();
if ("JPEG".equals(fileFormat)) {
writeParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
writeParam.setCompressionQuality(this.controller.getFileCompressionQuality());
}
FileImageOutputStream output = new FileImageOutputStream(file);
writer.setOutput(output);
writer.write(null, new IIOImage(image, null, null), writeParam);
writer.dispose();
output.close();
}Example 70
| Project: Galacticraft-master File: MapUtil.java View source code |
@SideOnly(Side.CLIENT)
public static void writeImgToFile(BufferedImage img, String name) {
if (GalacticraftCore.enableJPEG) {
File folder = new File(FMLClientHandler.instance().getClient().mcDataDir, "assets/galacticraftMaps");
try {
ImageOutputStream outputStreamA = new FileImageOutputStream(new File(folder, name));
GalacticraftCore.jpgWriter.setOutput(outputStreamA);
GalacticraftCore.jpgWriter.write(null, new IIOImage(img, null, null), GalacticraftCore.writeParam);
outputStreamA.close();
} catch (Exception e) {
}
}
}Example 71
| Project: JLatexMath-master File: TeXFormula.java View source code |
public void createImage(String format, int style, float size, String out, Color bg, Color fg, boolean transparency) {
TeXIcon icon = createTeXIcon(style, size);
icon.setInsets(new Insets(1, 1, 1, 1));
int w = icon.getIconWidth(), h = icon.getIconHeight();
BufferedImage image = new BufferedImage(w, h, transparency ? BufferedImage.TYPE_INT_ARGB : BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = image.createGraphics();
if (bg != null && !transparency) {
g2.setColor(bg);
g2.fillRect(0, 0, w, h);
}
icon.setForeground(fg);
icon.paintIcon(null, g2, 0, 0);
try {
FileImageOutputStream imout = new FileImageOutputStream(new File(out));
ImageIO.write(image, format, imout);
imout.flush();
imout.close();
} catch (IOException ex) {
System.err.println("I/O error : Cannot generate " + out);
}
g2.dispose();
}Example 72
| Project: CompendiumNG-master File: ProjectCompendiumFrame.java View source code |
//printScreenCode?? Might be useful to know?
//throws both AWTException and IOException
//BufferedImage image = new Robot().createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
/**
* Save the current map as a JPEG.
*/
public void onSaveAsJpeg() {
UIViewFrame frame = getCurrentFrame();
if (frame instanceof UIMapViewFrame) {
try {
//$NON-NLS-1$ //$NON-NLS-2$
UIFileFilter jpgFilter = new UIFileFilter(new String[] { "jpg" }, "JPEG Image Files");
UIFileChooser fileDialog = new UIFileChooser();
//$NON-NLS-1$
fileDialog.setDialogTitle(//$NON-NLS-1$
LanguageProperties.getString(LanguageProperties.UI_GENERAL_BUNDLE, "ProjectCompendiumFrame.enterFileName2"));
fileDialog.setFileFilter(jpgFilter);
fileDialog.setDialogType(JFileChooser.SAVE_DIALOG);
//$NON-NLS-1$
fileDialog.setRequiredExtension(//$NON-NLS-1$
".jpg");
// FIX FOR MAC - NEEDS '/' ON END TO DENOTE A FOLDER
// AND MUST USE ABSOLUTE PATH, AS RELATIVE PATH REMOVES THE '/'
//$NON-NLS-1$
File filepath = new File("");
String sPath = filepath.getAbsolutePath();
//$NON-NLS-1$
File file = new File(sPath + ProjectCompendium.sFS + "Exports" + ProjectCompendium.sFS);
if (file.exists()) {
fileDialog.setCurrentDirectory(file);
}
//$NON-NLS-1$
String //$NON-NLS-1$
fileName = "";
UIUtilities.centerComponent(fileDialog, this);
int retval = fileDialog.showDialog(this, null);
if (retval == JFileChooser.APPROVE_OPTION) {
if ((fileDialog.getSelectedFile()) != null) {
fileName = fileDialog.getSelectedFile().getAbsolutePath();
if (fileName != null) {
if (!//$NON-NLS-1$
fileName.toLowerCase().endsWith(//$NON-NLS-1$
".jpg")) {
//$NON-NLS-1$
fileName += ".jpg";
}
}
UIViewPane pane = ((UIMapViewFrame) frame).getViewPane();
Dimension size = pane.calculateSize();
BufferedImage img = (pane.getGraphicsConfiguration()).createCompatibleImage(size.width, size.height, Transparency.OPAQUE);
Graphics2D graphics = img.createGraphics();
pane.paint(graphics);
if (ProjectCompendium.isLinux) {
Iterator iter = //$NON-NLS-1$
ImageIO.getImageWritersByFormatName(//$NON-NLS-1$
"JPG");
if (iter.hasNext()) {
ImageWriter writer = (ImageWriter) iter.next();
ImageWriteParam iwp = writer.getDefaultWriteParam();
iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
iwp.setCompressionQuality(1);
File outFile = new File(fileName);
FileImageOutputStream output = new FileImageOutputStream(outFile);
writer.setOutput(output);
IIOImage image = new IIOImage(img, null, null);
writer.write(null, image, iwp);
}
} else {
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(fileName));
ImageIO.write(img, "jpeg", out);
out.close();
}
}
}
} catch (Exception ex) {
log.error("Error...", ex);
log.info("Exception creating map image = " + ex.getMessage());
}
}
}Example 73
| Project: GameMaker-HTML5-Player-master File: ghpframe.java View source code |
public void gmtohtml() {
//Read and convert file
proBar("Reading...");
File d = new File(ff.getText());
lf = d.getPath();
proBar(5);
if (d.exists() == false) {
proBar(0, "File doesn't exist.");
return;
}
String dir = d.getName();
proBar(7);
gmfile = lfc.openFile(d);
int rsnum = gmfile.sprites.size() + gmfile.sounds.size() + gmfile.backgrounds.size() + gmfile.paths.size() + gmfile.scripts.size() + gmfile.fonts.size() + gmfile.timelines.size() + gmfile.gmObjects.size() + gmfile.rooms.size();
proBar(10);
resourceNames = new String[rsnum];
objNames = new String[gmfile.gmObjects.size()];
int ind = 0;
for (GmObject o : gmfile.gmObjects) {
objNames[ind] = o.getName();
resourceNames[ind++] = o.getName();
}
for (Sprite s : gmfile.sprites) resourceNames[ind++] = s.getName();
for (Background b : gmfile.backgrounds) resourceNames[ind++] = b.getName();
for (Sound s : gmfile.sounds) resourceNames[ind++] = s.getName();
for (Room r : gmfile.rooms) resourceNames[ind++] = r.getName();
for (Timeline t : gmfile.timelines) resourceNames[ind++] = t.getName();
for (Path p : gmfile.paths) resourceNames[ind++] = p.getName();
for (Script s : gmfile.scripts) resourceNames[ind++] = s.getName();
for (Font f : gmfile.fonts) resourceNames[ind++] = f.getName();
Arrays.sort(resourceNames);
Arrays.sort(objNames);
//Get settings and other variables
String descr = gmfile.gameSettings.get(GameSettings.PGameSettings.DESCRIPTION);
int fps = gmfile.rooms.first().get(Room.PRoom.SPEED);
Iterator<Sprite> sprites = gmfile.sprites.iterator();
int sprnum = gmfile.sprites.size();
Iterator<Sound> sounds = gmfile.sounds.iterator();
int sndnum = gmfile.sounds.size();
Iterator<Background> backgrounds = gmfile.backgrounds.iterator();
int bcknum = gmfile.backgrounds.size();
Iterator<org.lateralgm.resources.Font> fonts = gmfile.fonts.iterator();
//int fntnum = gmfile.fonts.size();
Iterator<Script> scripts = gmfile.scripts.iterator();
//int scrnum = gmfile.scripts.size();
Iterator<GmObject> gmobjects = gmfile.gmObjects.iterator();
int objnum = gmfile.gmObjects.size();
Iterator<Room> rooms = gmfile.rooms.iterator();
int roomnum = gmfile.rooms.size();
//Add files
proBar("Adding JavaScript...");
File tmpdir = new File(d.getPath().substring(0, d.getPath().lastIndexOf(File.separator)) + File.separator + dir.substring(0, dir.lastIndexOf(".")));
File udir = new File(d.getPath().substring(0, d.getPath().lastIndexOf(File.separator)));
tmpdir.mkdir();
FileOutputStream li, re, main, event, func, mainjs, debug, vars;
byte buf;
String line;
try {
//LICENSE
File lisf = new File(tmpdir + "/LICENSE");
lisf.createNewFile();
li = new FileOutputStream(lisf);
InputStreamReader lif = new InputStreamReader(ghpc.class.getResourceAsStream("/LICENSE"));
while (lif.ready()) {
buf = (byte) lif.read();
li.write(buf);
}
li.close();
lif.close();
//README
File resf = new File(tmpdir + "/README");
resf.createNewFile();
re = new FileOutputStream(resf);
InputStreamReader ref = new InputStreamReader(ghpc.class.getResourceAsStream("/README"));
while (ref.ready()) {
buf = (byte) ref.read();
re.write(buf);
}
re.close();
lif.close();
//main.html
File mainsf = new File(tmpdir + "/main.html");
mainsf.createNewFile();
main = new FileOutputStream(mainsf);
InputStreamReader[] mainf = new InputStreamReader[4];
mainf[0] = new InputStreamReader(ghpc.class.getResourceAsStream("src/mainf0"));
while (mainf[0].ready()) {
buf = (byte) mainf[0].read();
main.write(buf);
}
mainf[0].close();
for (int i = 0; i < dir.substring(0, dir.lastIndexOf(".")).length(); i++) {
buf = (byte) dir.substring(0, dir.lastIndexOf(".")).toCharArray()[i];
main.write(buf);
}
mainf[1] = new InputStreamReader(ghpc.class.getResourceAsStream("src/mainf1"));
while (mainf[1].ready()) {
buf = (byte) mainf[1].read();
main.write(buf);
}
mainf[1].close();
for (int i = 0; i < descr.length(); i++) {
buf = (byte) descr.toCharArray()[i];
main.write(buf);
}
mainf[2] = new InputStreamReader(ghpc.class.getResourceAsStream("src/mainf2"));
while (mainf[2].ready()) {
buf = (byte) mainf[2].read();
main.write(buf);
}
mainf[2].close();
String cur = "";
if (!(boolean) gmfile.gameSettings.get(PGameSettings.DISPLAY_CURSOR))
cur = "cursor:url(invis.png),auto;";
line = "<canvas id=\"maincan\" width=\"" + gmfile.rooms.first().get(PRoom.WIDTH) + "\" height=\"" + gmfile.rooms.first().get(PRoom.HEIGHT) + "\" tabindex=\"1\" style=\"" + cur + "\" onkeydown=\"eventKeyboardPress(event);\" onkeyup=\"eventKeyboardRelease(event);\" onmousemove=\"eventMouseMove(event);\" onmousedown=\"eventMousePress(event);\" onmouseup=\"eventMouseRelease(event);\">";
for (int e = 0; e < line.length(); e++) {
buf = (byte) line.toCharArray()[e];
main.write(buf);
}
mainf[3] = new InputStreamReader(ghpc.class.getResourceAsStream("src/mainf3"));
while (mainf[3].ready()) {
buf = (byte) mainf[3].read();
main.write(buf);
}
mainf[3].close();
if (dc.isSelected()) {
line = "\t\t<script type=\"text/javascript\" src=\"debug.js\"></script>\n";
for (int e = 0; e < line.length(); e++) {
buf = (byte) line.toCharArray()[e];
main.write(buf);
}
}
line = "\n\t</body>\n</html>";
for (int e = 0; e < line.length(); e++) {
buf = (byte) line.toCharArray()[e];
main.write(buf);
}
main.close();
proBar(11);
//Browser icons/main dir imgs
BufferedImage[] bric = new BufferedImage[10];
FileOutputStream brics = new FileOutputStream(tmpdir + "/chrome.png");
bric[0] = ImageIO.read(ghpc.class.getResourceAsStream("src/bric0.png"));
ImageIO.write(bric[0], "png", brics);
brics.close();
brics = new FileOutputStream(tmpdir + "/firefox.png");
bric[1] = ImageIO.read(ghpc.class.getResourceAsStream("src/bric1.png"));
ImageIO.write((RenderedImage) bric[1], "png", brics);
brics.close();
brics = new FileOutputStream(tmpdir + "/safari.png");
bric[2] = ImageIO.read(ghpc.class.getResourceAsStream("src/bric2.png"));
ImageIO.write((RenderedImage) bric[2], "png", brics);
brics.close();
brics = new FileOutputStream(tmpdir + "/opera.png");
bric[3] = ImageIO.read(ghpc.class.getResourceAsStream("src/bric3.png"));
ImageIO.write((RenderedImage) bric[3], "png", brics);
brics.close();
brics = new FileOutputStream(tmpdir + "/invis.png");
bric[4] = ImageIO.read(ghpc.class.getResourceAsStream("src/invis"));
ImageIO.write((RenderedImage) bric[4], "png", brics);
brics.close();
//Particles
BufferedImage[] part = new BufferedImage[16];
File partf = new File(tmpdir + "/particles");
partf.mkdir();
FileOutputStream parts = new FileOutputStream(tmpdir + "/particles/00_pixel.png");
part[0] = ImageIO.read(ghpc.class.getResourceAsStream("src/particles/part00.png"));
ImageIO.write(part[0], "png", parts);
parts.close();
parts = new FileOutputStream(tmpdir + "/particles/01_disk.png");
part[0] = ImageIO.read(ghpc.class.getResourceAsStream("src/particles/part01.png"));
ImageIO.write(part[0], "png", parts);
parts.close();
parts = new FileOutputStream(tmpdir + "/particles/02_square.png");
part[0] = ImageIO.read(ghpc.class.getResourceAsStream("src/particles/part02.png"));
ImageIO.write(part[0], "png", parts);
parts.close();
parts = new FileOutputStream(tmpdir + "/particles/03_line.png");
part[0] = ImageIO.read(ghpc.class.getResourceAsStream("src/particles/part03.png"));
ImageIO.write(part[0], "png", parts);
parts.close();
parts = new FileOutputStream(tmpdir + "/particles/04_star.png");
part[0] = ImageIO.read(ghpc.class.getResourceAsStream("src/particles/part04.png"));
ImageIO.write(part[0], "png", parts);
parts.close();
parts = new FileOutputStream(tmpdir + "/particles/05_circle.png");
part[0] = ImageIO.read(ghpc.class.getResourceAsStream("src/particles/part05.png"));
ImageIO.write(part[0], "png", parts);
parts.close();
parts = new FileOutputStream(tmpdir + "/particles/06_ring.png");
part[0] = ImageIO.read(ghpc.class.getResourceAsStream("src/particles/part06.png"));
ImageIO.write(part[0], "png", parts);
parts.close();
parts = new FileOutputStream(tmpdir + "/particles/07_sphere.png");
part[0] = ImageIO.read(ghpc.class.getResourceAsStream("src/particles/part07.png"));
ImageIO.write(part[0], "png", parts);
parts.close();
parts = new FileOutputStream(tmpdir + "/particles/08_flare.png");
part[0] = ImageIO.read(ghpc.class.getResourceAsStream("src/particles/part08.png"));
ImageIO.write(part[0], "png", parts);
parts.close();
parts = new FileOutputStream(tmpdir + "/particles/09_spark.png");
part[0] = ImageIO.read(ghpc.class.getResourceAsStream("src/particles/part09.png"));
ImageIO.write(part[0], "png", parts);
parts.close();
parts = new FileOutputStream(tmpdir + "/particles/10_explosion.png");
part[0] = ImageIO.read(ghpc.class.getResourceAsStream("src/particles/part10.png"));
ImageIO.write(part[0], "png", parts);
parts.close();
parts = new FileOutputStream(tmpdir + "/particles/11_cloud.png");
part[0] = ImageIO.read(ghpc.class.getResourceAsStream("src/particles/part11.png"));
ImageIO.write(part[0], "png", parts);
parts.close();
parts = new FileOutputStream(tmpdir + "/particles/12_smoke.png");
part[0] = ImageIO.read(ghpc.class.getResourceAsStream("src/particles/part12.png"));
ImageIO.write(part[0], "png", parts);
parts.close();
parts = new FileOutputStream(tmpdir + "/particles/13_snow.png");
part[0] = ImageIO.read(ghpc.class.getResourceAsStream("src/particles/part13.png"));
ImageIO.write(part[0], "png", parts);
parts.close();
proBar(12);
//event.js, func.js, main.js, debug.js
File eventsf = new File(tmpdir + "/event.js");
eventsf.createNewFile();
event = new FileOutputStream(eventsf);
InputStreamReader eventf = new InputStreamReader(ghpc.class.getResourceAsStream("src/eventf"));
while (eventf.ready()) {
buf = (byte) eventf.read();
event.write(buf);
}
event.close();
eventf.close();
File funcsf = new File(tmpdir + "/func.js");
funcsf.createNewFile();
func = new FileOutputStream(funcsf);
InputStreamReader funcf = new InputStreamReader(ghpc.class.getResourceAsStream("src/funcf"));
while (funcf.ready()) {
buf = (byte) funcf.read();
func.write(buf);
}
func.close();
funcf.close();
File mainjsf = new File(tmpdir + "/main.js");
mainjsf.createNewFile();
mainjs = new FileOutputStream(mainjsf);
InputStreamReader mainjf = new InputStreamReader(ghpc.class.getResourceAsStream("src/mainjf"));
while (mainjf.ready()) {
buf = (byte) mainjf.read();
mainjs.write(buf);
}
mainjs.close();
mainjf.close();
if (dc.isSelected()) {
File debugsf = new File(tmpdir + "/debug.js");
debugsf.createNewFile();
debug = new FileOutputStream(debugsf);
InputStreamReader debugf = new InputStreamReader(ghpc.class.getResourceAsStream("src/debugf"));
while (debugf.ready()) {
buf = (byte) debugf.read();
debug.write(buf);
}
debugf.close();
}
proBar(13);
//vars.js
File varsf = new File(tmpdir + "/vars.js");
varsf.createNewFile();
vars = new FileOutputStream(varsf);
InputStreamReader[] varf = new InputStreamReader[10];
varf[0] = new InputStreamReader(ghpc.class.getResourceAsStream("src/varf0"));
while (varf[0].ready()) {
buf = (byte) varf[0].read();
vars.write(buf);
}
varf[0].close();
for (int i = 0; i < Integer.toString(fps).length(); i++) {
buf = (byte) Integer.toString(fps).toCharArray()[i];
vars.write(buf);
}
varf[1] = new InputStreamReader(ghpc.class.getResourceAsStream("src/varf1"));
while (varf[1].ready()) {
buf = (byte) varf[1].read();
vars.write(buf);
}
varf[1].close();
while (sprites.hasNext()) {
Sprite spr = sprites.next();
String sh = "";
if (spr.get(PSprite.SHAPE).equals(MaskShape.PRECISE))
sh = "PRECISE";
if (spr.get(PSprite.SHAPE).equals(MaskShape.RECTANGLE))
sh = "RECTANGLE";
if (spr.get(PSprite.SHAPE).equals(MaskShape.DISK))
sh = "ELLIPSE";
if (spr.get(PSprite.SHAPE).equals(MaskShape.DIAMOND))
sh = "DIAMOND";
line = spr.getName() + " = Sprite(\"sprites/" + spr.getName() + ".png\", " + spr.subImages.size() + ", " + spr.get(PSprite.TRANSPARENT) + ", " + spr.get(PSprite.SMOOTH_EDGES) + ", " + spr.get(PSprite.ORIGIN_X) + ", " + spr.get(PSprite.ORIGIN_Y) + ", " + spr.get(PSprite.BB_LEFT) + ", " + spr.get(PSprite.BB_RIGHT) + ", " + spr.get(PSprite.BB_TOP) + ", " + spr.get(PSprite.BB_BOTTOM) + ", " + sh + ", " + spr.get(PSprite.ALPHA_TOLERANCE) + ");\n";
for (int e = 0; e < line.length(); e++) {
buf = (byte) line.toCharArray()[e];
vars.write(buf);
}
}
line = "\n//Sounds\n";
for (int e = 0; e < line.length(); e++) {
buf = (byte) line.toCharArray()[e];
vars.write(buf);
}
while (sounds.hasNext()) {
String sndname = sounds.next().getName();
line = sndname + " = new Audio();\n" + sndname + ".src = \"sounds/" + sndname + ".wav\";\n" + sndname + ".load();\n";
for (int e = 0; e < line.length(); e++) {
buf = (byte) line.toCharArray()[e];
vars.write(buf);
}
}
line = "\n//Backgrounds\n";
for (int e = 0; e < line.length(); e++) {
buf = (byte) line.toCharArray()[e];
vars.write(buf);
}
while (backgrounds.hasNext()) {
String bckname = backgrounds.next().getName();
line = bckname + " = new Image();\n" + bckname + ".src = \"backgrounds/" + bckname + ".png\";\n";
for (int e = 0; e < line.length(); e++) {
buf = (byte) line.toCharArray()[e];
vars.write(buf);
}
}
line = "\n//Fonts\n";
for (int e = 0; e < line.length(); e++) {
buf = (byte) line.toCharArray()[e];
vars.write(buf);
}
while (fonts.hasNext()) {
org.lateralgm.resources.Font fnt = fonts.next();
line = fnt.getName() + " = fontAdd(\"" + fnt.get(PFont.FONT_NAME) + "\", " + fnt.get(PFont.SIZE) + ", " + fnt.get(PFont.BOLD) + ", " + fnt.get(PFont.ITALIC) + ");\n";
for (int e = 0; e < line.length(); e++) {
buf = (byte) line.toCharArray()[e];
vars.write(buf);
}
}
line = "\n//Scripts\n";
for (int e = 0; e < line.length(); e++) {
buf = (byte) line.toCharArray()[e];
vars.write(buf);
}
while (scripts.hasNext()) {
org.lateralgm.resources.Script scr = scripts.next();
if (gmhescr.contains(scr.getName())) {
continue;
}
line = "function " + scr.getName() + "() {\n" + gmltoghp(scr.getCode(), "this", "\t") + "\n}\n";
for (int e = 0; e < line.length(); e++) {
buf = (byte) line.toCharArray()[e];
vars.write(buf);
}
}
proBar(14);
///////////
//Objects//
///////////
line = "\n//Objects\n";
//Begin Step
boolean ie = false;
while (gmobjects.hasNext()) {
GmObject curobj = gmobjects.next();
GmObject qobj = curobj;
boolean cont = false;
while (qobj != null) {
for (org.lateralgm.resources.sub.Event e : qobj.mainEvents.get(MainEvent.EV_STEP).events) if (e.toString().equals("Begin Step")) {
cont = true;
break;
}
if (cont)
break;
ResourceReference ref2 = qobj.get(PGmObject.PARENT);
if (ref2 == null)
qobj = null;
else
qobj = (GmObject) ref2.get();
}
if (!cont)
continue;
if (!ie)
line += "function objBeginStep() {\n";
line += "\t" + curobj.getName() + ".BeginStep();\n";
ie = true;
}
if (ie)
line += "}\n\n";
else
line += "function objBeginStep(){}\n";
for (int e = 0; e < line.length(); e++) {
buf = (byte) line.toCharArray()[e];
vars.write(buf);
}
//Normal Step
line = "";
ie = false;
gmobjects = gmfile.gmObjects.iterator();
while (gmobjects.hasNext()) {
GmObject curobj = gmobjects.next();
if (!ie)
line += "function objStep() {\n";
line += "\t" + curobj.getName() + ".Step();\n";
ie = true;
}
if (ie)
line += "}\n\n";
else
line += "function objStep(){}\n";
for (int e = 0; e < line.length(); e++) {
buf = (byte) line.toCharArray()[e];
vars.write(buf);
}
//End Step
line = "";
ie = false;
gmobjects = gmfile.gmObjects.iterator();
while (gmobjects.hasNext()) {
GmObject curobj = gmobjects.next();
GmObject qobj = curobj;
boolean cont = false;
while (qobj != null) {
for (org.lateralgm.resources.sub.Event e : qobj.mainEvents.get(MainEvent.EV_STEP).events) if (e.toString().equals("Begin Step")) {
cont = true;
break;
}
if (cont)
break;
ResourceReference ref2 = qobj.get(PGmObject.PARENT);
if (ref2 == null)
qobj = null;
else
qobj = (GmObject) ref2.get();
}
if (!cont)
continue;
if (!ie)
line += "function objEndStep() {\n";
line += "\t" + curobj.getName() + ".EndStep();\n";
ie = true;
}
if (ie)
line += "}\n\n";
else
line += "function objEndStep(){}\n";
for (int e = 0; e < line.length(); e++) {
buf = (byte) line.toCharArray()[e];
vars.write(buf);
}
//Mouse Events
String[] mLocales = { "", "Global " };
String[] mButtons = { "Left ", "Middle ", "Right " };
String[] mActions = { "Button", "Pressed", "Released" };
for (String ml : mLocales) for (String mb : mButtons) for (String ma : mActions) {
String eName = ml + mb + ma;
line = "";
ie = false;
gmobjects = gmfile.gmObjects.iterator();
while (gmobjects.hasNext()) {
GmObject curobj = gmobjects.next();
GmObject qobj = curobj;
boolean cont = false;
while (qobj != null) {
for (org.lateralgm.resources.sub.Event e : qobj.mainEvents.get(MainEvent.EV_MOUSE).events) if (e.toString().equals(eName)) {
cont = true;
break;
}
if (cont)
break;
ResourceReference ref2 = qobj.get(PGmObject.PARENT);
if (ref2 == null)
qobj = null;
else
qobj = (GmObject) ref2.get();
}
if (!cont)
continue;
if (!ie)
line += "function obj" + eName.replace(" ", "") + "() {\n";
line += "\t" + curobj.getName() + "." + eName.replace(" ", "") + "();\n";
ie = true;
}
if (ie)
line += "}\n\n";
else
line += "function obj" + eName.replace(" ", "") + "() {}\n";
for (int e = 0; e < line.length(); e++) {
buf = (byte) line.toCharArray()[e];
vars.write(buf);
}
}
//Keyboard
line = "";
ie = false;
gmobjects = gmfile.gmObjects.iterator();
while (gmobjects.hasNext()) {
GmObject curobj = gmobjects.next();
GmObject qobj = curobj;
boolean cont = false;
while (qobj != null) {
if (qobj.mainEvents.get(MainEvent.EV_KEYBOARD).events.size() > 0) {
cont = true;
break;
}
ResourceReference ref2 = qobj.get(PGmObject.PARENT);
if (ref2 == null)
qobj = null;
else
qobj = (GmObject) ref2.get();
}
if (!cont)
continue;
if (!ie)
line += "function objKeys(i) {\n";
line += "\t" + curobj.getName() + ".Keyboard(i);\n";
ie = true;
}
if (ie)
line += "}\n\n";
else
line += "function objKeys(){}\n";
for (int e = 0; e < line.length(); e++) {
buf = (byte) line.toCharArray()[e];
vars.write(buf);
}
//Keyboard Press
line = "";
ie = false;
gmobjects = gmfile.gmObjects.iterator();
while (gmobjects.hasNext()) {
GmObject curobj = gmobjects.next();
GmObject qobj = curobj;
boolean cont = false;
while (qobj != null) {
if (qobj.mainEvents.get(MainEvent.EV_KEYPRESS).events.size() > 0) {
cont = true;
break;
}
ResourceReference ref2 = qobj.get(PGmObject.PARENT);
if (ref2 == null)
qobj = null;
else
qobj = (GmObject) ref2.get();
}
if (!cont)
continue;
if (!ie)
line += "function objKeyP(i) {\n";
line += "\t" + curobj.getName() + ".KeyboardPress(i);\n";
ie = true;
}
if (ie)
line += "}\n\n";
else
line += "function objKeyP(){}\n";
for (int e = 0; e < line.length(); e++) {
buf = (byte) line.toCharArray()[e];
vars.write(buf);
}
//Keyboard Release
line = "";
ie = false;
gmobjects = gmfile.gmObjects.iterator();
while (gmobjects.hasNext()) {
GmObject curobj = gmobjects.next();
GmObject qobj = curobj;
boolean cont = false;
while (qobj != null) {
if (qobj.mainEvents.get(MainEvent.EV_KEYRELEASE).events.size() > 0) {
cont = true;
break;
}
ResourceReference ref2 = qobj.get(PGmObject.PARENT);
if (ref2 == null)
qobj = null;
else
qobj = (GmObject) ref2.get();
}
if (!cont)
continue;
if (!ie)
line += "function objKeyR(i) {\n";
line += "\t" + curobj.getName() + ".KeyboardRelease(i);\n";
ie = true;
}
if (ie)
line += "}\n\n";
else
line += "function objKeyR(){}\n";
for (int e = 0; e < line.length(); e++) {
buf = (byte) line.toCharArray()[e];
vars.write(buf);
}
//Room Start
line = "";
ie = false;
gmobjects = gmfile.gmObjects.iterator();
while (gmobjects.hasNext()) {
GmObject curobj = gmobjects.next();
GmObject qobj = curobj;
boolean cont = false;
while (qobj != null) {
for (org.lateralgm.resources.sub.Event e : qobj.mainEvents.get(MainEvent.EV_OTHER).events) if (e.toString().equals("Room Start")) {
cont = true;
break;
}
if (cont)
break;
ResourceReference ref2 = qobj.get(PGmObject.PARENT);
if (ref2 == null)
qobj = null;
else
qobj = (GmObject) ref2.get();
}
if (!cont)
continue;
if (!ie)
line += "function objRoomStart() {\n";
line += "\t" + curobj.getName() + ".RoomStart();\n";
ie = true;
}
if (ie)
line += "}\n\n";
else
line += "function objRoomStart(){}\n";
for (int e = 0; e < line.length(); e++) {
buf = (byte) line.toCharArray()[e];
vars.write(buf);
}
//Room End
line = "";
ie = false;
gmobjects = gmfile.gmObjects.iterator();
while (gmobjects.hasNext()) {
GmObject curobj = gmobjects.next();
GmObject qobj = curobj;
boolean cont = false;
while (qobj != null) {
for (org.lateralgm.resources.sub.Event e : qobj.mainEvents.get(MainEvent.EV_OTHER).events) if (e.toString().equals("Room End")) {
cont = true;
break;
}
if (cont)
break;
ResourceReference ref2 = qobj.get(PGmObject.PARENT);
if (ref2 == null)
qobj = null;
else
qobj = (GmObject) ref2.get();
}
if (!cont)
continue;
if (!ie)
line += "function objRoomEnd() {\n";
line += "\t" + curobj.getName() + ".RoomEnd();\n";
ie = true;
}
if (ie)
line += "}\n\n";
else
line += "function objRoomEnd(){}\n";
for (int e = 0; e < line.length(); e++) {
buf = (byte) line.toCharArray()[e];
vars.write(buf);
}
//Object
line = "";
int i = 0;
gmobjects = gmfile.gmObjects.iterator();
while (gmobjects.hasNext()) {
GmObject curobj = gmobjects.next();
i++;
String objname = curobj.getName();
line = "//" + objname + "\n" + objname + " = function() {\n //Do nothing\n}\n\n" + objname + ".id = new Array();\n\n" + objname + ".Create = function(i, x, y) {\n " + objname + ".id[i] = new Array();\n " + objname + ".id[i][\"x\"] = x;\n " + objname + ".id[i][\"y\"] = y;\n " + objname + ".id[i][\"startx\"] = x;\n " + objname + ".id[i][\"starty\"] = y;\n\t" + objname + ".id[i][\"depth\"] = " + curobj.get(GmObject.PGmObject.DEPTH) + ";\n\t" + objname + ".id[i][\"visible\"] = " + curobj.get(GmObject.PGmObject.VISIBLE) + ";\n\t" + objname + ".id[i][\"objectIndex\"] = " + objname + ";\n\t";
String spr = "-1";
if (curobj.get(GmObject.PGmObject.SPRITE) != null)
spr = ((ResourceReference) curobj.get(GmObject.PGmObject.SPRITE)).get().getName();
line += objname + ".id[i][\"sprite\"] = " + spr + ";\n\t";
String mask = "-1";
if (curobj.get(GmObject.PGmObject.MASK) != null)
mask = ((ResourceReference) curobj.get(GmObject.PGmObject.MASK)).get().getName();
line += objname + ".id[i][\"mask\"] = " + mask + ";\n\t";
line += objname + ".id[i][\"imgIndex\"] = 0;\n\t" + objname + ".id[i][\"imgSpeed\"] = 1;\n\t";
line += objname + ".id[i][\"imgXscale\"] = 1;\n\t" + objname + ".id[i][\"imgYscale\"] = 1;\n\t";
line += objname + ".id[i][\"imgAngle\"] = 0;\n\t";
line += objname + ".id[i][\"persistent\"] = " + curobj.get(PGmObject.PERSISTENT) + ";\n\t";
line += objname + ".id[i][\"alarm\"] = new Array();\n\t";
line += objname + ".id[i][\"alarm\"][0] = -1;\n\t";
line += objname + ".id[i][\"alarm\"][1] = -1;\n\t";
line += objname + ".id[i][\"alarm\"][2] = -1;\n\t";
line += objname + ".id[i][\"alarm\"][3] = -1;\n\t";
line += objname + ".id[i][\"alarm\"][4] = -1;\n\t";
line += objname + ".id[i][\"alarm\"][5] = -1;\n\t";
line += objname + ".id[i][\"alarm\"][6] = -1;\n\t";
line += objname + ".id[i][\"alarm\"][7] = -1;\n\t";
line += objname + ".id[i][\"alarm\"][8] = -1;\n\t";
line += objname + ".id[i][\"alarm\"][9] = -1;\n\t";
line += objname + ".id[i][\"alarm\"][10] = -1;\n\t";
line += objname + ".id[i][\"alarm\"][11] = -1;\n";
if (curobj.mainEvents.get(MainEvent.EV_CREATE).events.size() > 0) {
Iterator<org.lateralgm.resources.sub.Event> ev_create = curobj.mainEvents.get(MainEvent.EV_CREATE).events.iterator();
while (ev_create.hasNext()) {
org.lateralgm.resources.sub.Event ev_cur = ev_create.next();
Iterator<org.lateralgm.resources.sub.Action> ev_actions = ev_cur.actions.iterator();
while (ev_actions.hasNext()) {
org.lateralgm.resources.sub.Action action = ev_actions.next();
Iterator<Argument> eab = action.getArguments().iterator();
while (eab.hasNext()) {
Argument arg = eab.next();
if ((arg.kind == Argument.ARG_STRING) && (!Character.isDigit(arg.getVal().charAt(0))))
line += "\t" + gmltoghp(arg.getVal(), objname, "\t").trim() + "\n";
else
line += " //Sorry no DnD support yet\n";
}
}
}
}
line += "\t" + objname + ".id[i][\"glin\"] = glin.length;\n";
line += "\tglin[glin.length] = " + objname + ".id[i];\n";
line += "}\n\n";
for (int e = 0; e < line.length(); e++) {
buf = (byte) line.toCharArray()[e];
vars.write(buf);
}
proBar(Math.round(15 + (2 * i / objnum)));
//Process events.
processEvent(curobj, objname, MainEvent.EV_DESTROY, vars);
processEvent(curobj, objname, MainEvent.EV_ALARM, vars);
processEvent(curobj, objname, MainEvent.EV_STEP, vars);
processEvent(curobj, objname, MainEvent.EV_COLLISION, vars);
processEvent(curobj, objname, MainEvent.EV_KEYBOARD, vars);
processEvent(curobj, objname, MainEvent.EV_KEYPRESS, vars);
processEvent(curobj, objname, MainEvent.EV_KEYPRESS, vars);
processEvent(curobj, objname, MainEvent.EV_MOUSE, vars);
processEvent(curobj, objname, MainEvent.EV_OTHER, vars);
processEvent(curobj, objname, MainEvent.EV_DRAW, vars);
processEvent(curobj, objname, MainEvent.EV_TRIGGER, vars);
}
/////////
//Rooms//
/////////
line = "//Rooms\n\n";
i = 0;
while (rooms.hasNext()) {
Room rm = rooms.next();
line = "//" + rm.getName() + "\n" + rm.getName() + " = " + i + ";\nresource[8][" + i + "] = function(i) {\n //Do nothing\n}\n\nresource[8][" + i + "].inst = new Array();\nresource[8][" + i + "].tiles = new Array();\n\nresource[8][" + i + "].rmCrCode = ";
if ((rm.get(PRoom.CREATION_CODE) == null) || (rm.get(PRoom.CREATION_CODE) == ""))
line += "false;\n\n";
else
line += "function() {\n" + gmltoghp(rm.get(PRoom.CREATION_CODE).toString(), "", "\t") + "\n}\n\n";
Iterator<Instance> rmi = rm.instances.iterator();
boolean icc = false;
line += "resource[8][" + i + "].objCrCode = ";
while (rmi.hasNext()) {
Instance inst = rmi.next();
if ((inst.properties.get(PInstance.CREATION_CODE) != null) && (inst.properties.get(PInstance.CREATION_CODE) != "")) {
if (icc)
line += gmltoghp(inst.getCreationCode(), "", "\t");
else
line += "function() {\n with (" + inst.properties.get(PInstance.ID) + ") {\n " + gmltoghp(inst.getCreationCode(), "", "\t").replace("\n", "\n ") + "\n }\n";
icc = true;
}
}
if (!icc)
line += "false;\n\n";
else
line += "}\n\n";
line += "resource[8][" + i + "].width = " + rm.get(PRoom.WIDTH) + ";\nresource[8][" + i + "].height = " + rm.get(PRoom.HEIGHT) + ";\nresource[8][" + i + "].backgroundColor = " + colorToJS((Color) rm.get(PRoom.BACKGROUND_COLOR)) + ";\nresource[8][" + i + "].drawBackgroundColor = " + rm.get(PRoom.DRAW_BACKGROUND_COLOR) + ";\n\n";
//Backgrounds
line += "resource[8][" + i + "].backgrounds = new Array();\n";
for (int e = 0; e < rm.backgroundDefs.size(); e++) {
BackgroundDef def = rm.backgroundDefs.get(e);
ResourceReference ref2 = (ResourceReference) def.properties.get(PBackgroundDef.BACKGROUND);
if (ref2 == null)
continue;
String bkg = ((ResourceReference) def.properties.get(PBackgroundDef.BACKGROUND)).get().getName();
boolean vis = def.properties.get(PBackgroundDef.VISIBLE);
boolean fore = def.properties.get(PBackgroundDef.FOREGROUND);
int x = def.properties.get(PBackgroundDef.X);
int y = def.properties.get(PBackgroundDef.Y);
boolean tileH = def.properties.get(PBackgroundDef.TILE_HORIZ);
boolean tileV = def.properties.get(PBackgroundDef.TILE_VERT);
boolean stretch = def.properties.get(PBackgroundDef.STRETCH);
int hsp = def.properties.get(PBackgroundDef.H_SPEED);
int vsp = def.properties.get(PBackgroundDef.V_SPEED);
line += "resource[8][" + i + "].backgrounds[" + e + "] = new RoomBackground(" + bkg + ", " + vis + ", " + fore + ", " + x + ", " + y + ", " + tileH + ", " + tileV + ", " + stretch + ", " + hsp + ", " + vsp + ");\n";
}
line += "\n";
line += "resource[8][" + i + "].Create = function() {\n\t//Instances\n";
rmi = rm.instances.iterator();
int e = 0;
while (rmi.hasNext()) {
Instance inst = rmi.next();
line += "\tresource[8][" + i + "].inst[" + e + "] = new Array();\n\tresource[8][" + i + "].inst[" + e + "][0] = " + deRef((ResourceReference<?>) inst.properties.get(PInstance.OBJECT)) + ";\n\tresource[8][" + i + "].inst[" + e + "][1] = " + inst.getPosition().x + ";\n\tresource[8][" + i + "].inst[" + e + "][2] = " + inst.getPosition().y + ";\n";
e++;
}
Iterator<Tile> tiles = rm.tiles.iterator();
line += "\n\t//Tiles\n";
e = 0;
while (tiles.hasNext()) {
Tile t = tiles.next();
line += "\tresource[8][" + i + "].tiles[" + e + "] = new Array();\n";
line += "\tresource[8][" + i + "].tiles[" + e + "][0] = " + ((ResourceReference) t.properties.get(PTile.BACKGROUND)).get().getName() + ";\n";
line += "\tresource[8][" + i + "].tiles[" + e + "][1] = " + t.getBackgroundPosition().x + ";\n";
line += "\tresource[8][" + i + "].tiles[" + e + "][2] = " + t.getBackgroundPosition().y + ";\n";
line += "\tresource[8][" + i + "].tiles[" + e + "][3] = " + t.getSize().width + ";\n";
line += "\tresource[8][" + i + "].tiles[" + e + "][4] = " + t.getSize().height + ";\n";
line += "\tresource[8][" + i + "].tiles[" + e + "][5] = " + t.getRoomPosition().x + ";\n";
line += "\tresource[8][" + i + "].tiles[" + e + "][6] = " + t.getRoomPosition().y + ";\n";
line += "\tresource[8][" + i + "].tiles[" + e + "][7] = " + t.getDepth() + ";\n";
e++;
}
line += "}" + (rooms.hasNext() ? "\n\n" : "");
for (e = 0; e < line.length(); e++) {
buf = (byte) line.toCharArray()[e];
vars.write(buf);
}
proBar(Math.round(18 + (2 * ++i / roomnum)));
}
} catch (IOException e) {
System.out.println("Could not include files.");
return;
}
//Add sprites
proBar("Converting Sprites...");
File sprdir = new File(tmpdir + "/sprites");
sprdir.mkdir();
proBar(20);
sprites = gmfile.sprites.iterator();
for (int i = 0; sprites.hasNext(); i++) {
Sprite sprname = sprites.next();
try {
ImageOutputStream spr = new FileImageOutputStream(new File(sprdir.getPath() + "/" + sprname.toString() + ".png"));
if (sprname.subImages.get(0) == null) {
spr.close();
continue;
}
BufferedImage img = new BufferedImage(sprname.getDisplayImage().getWidth() * sprname.subImages.size(), sprname.getDisplayImage().getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics g = img.getGraphics();
g.drawImage(sprname.subImages.get(0), 0, 0, this);
for (int e = 1; e < sprname.subImages.size(); e++) {
g.drawImage(sprname.subImages.get(e), sprname.getDisplayImage().getWidth() * e, 0, this);
}
ImageIO.write((RenderedImage) img, "png", spr);
spr.close();
} catch (IOException e) {
System.out.println("Could not include " + sprname.toString() + ".");
}
proBar(Math.round(22 + (2 * i / sprnum)));
}
if (sprnum == 0) {
sprdir.delete();
}
//Add sounds
proBar("Converting Sounds...");
File snddir = new File(tmpdir + "/sounds");
snddir.mkdir();
proBar(25);
sounds = gmfile.sounds.iterator();
for (int i = 0; sounds.hasNext(); i++) {
Sound sndname = sounds.next();
try {
FileOutputStream snd = new FileOutputStream(snddir.getPath() + "/" + sndname.toString() + ".wav");
byte[] aud = gmfile.sounds.get(sndname.toString()).data;
if (aud == null) {
snd.close();
continue;
}
snd.write(aud);
snd.close();
} catch (IOException e) {
System.out.println("Could not include " + sndname + ".");
}
proBar(Math.round(27 + (2 * i / sndnum)));
}
if (sndnum == 0) {
snddir.delete();
}
//Add backgrounds
proBar("Converting Backgrounds...");
File bckdir = new File(tmpdir + "/backgrounds");
bckdir.mkdir();
proBar(30);
backgrounds = gmfile.backgrounds.iterator();
for (int i = 0; backgrounds.hasNext(); i++) {
Background bckname = backgrounds.next();
try {
FileOutputStream bck = new FileOutputStream(bckdir.getPath() + "/" + bckname.toString() + ".png");
BufferedImage bimg = gmfile.backgrounds.get(bckname.toString()).getDisplayImage();
if (bimg == null) {
bck.close();
continue;
}
ImageIO.write(bimg, "png", bck);
bck.close();
} catch (IOException e) {
System.out.println("Could not include " + bckname + ".");
}
proBar(Math.round(32 + (2 * i / bcknum)));
}
if (bcknum == 0) {
bckdir.delete();
}
//Add paths
proBar("Converting Paths...");
Iterator<Path> paths = gmfile.paths.iterator();
int pathnum = gmfile.paths.size();
proBar(35);
for (int i = 0; paths.hasNext(); i++) {
Path pathname = paths.next();
try {
int pnum = pathname.points.size();
if (pnum == 0) {
return;
}
//Write to file
vars.write(null);
} catch (IOException e) {
System.out.println("Could not include " + pathname + ".");
}
proBar(Math.round(37 + (2 * i / pathnum)));
}
if (pathnum == 0) {
//Do something?
}
//Add to zip
dir = dir.substring(0, dir.lastIndexOf("."));
if (!zc.isSelected()) {
proBar(100, "Done!");
try {
vars.close();
} catch (IOException err) {
System.out.println("Could not close files.");
}
try {
if (System.getProperty("os.name").indexOf("Windows") != -1) {
Runtime.getRuntime().exec("explorer /e /select," + udir + "\\" + dir);
} else if (System.getProperty("os.name").indexOf("Linux") != -1) {
Runtime.getRuntime().exec("xdg-open " + udir + "/" + dir);
} else if (System.getProperty("os.name").indexOf("Mac") != -1) {
Runtime.getRuntime().exec("/usr/bin/open " + udir + "/" + dir);
}
} catch (IOException err) {
System.out.println("Couldn't open " + udir + "/" + dir + ".");
}
return;
}
proBar(0, "Packing into zip...");
d = tmpdir;
String[] entries = d.list();
byte[] buffer = new byte[4096];
int bytesRead;
ZipOutputStream out = null;
FileInputStream in = null;
ZipEntry entry = null;
File f = null;
try {
out = new ZipOutputStream(new FileOutputStream(udir + "/" + dir + ".zip"));
} catch (FileNotFoundException err) {
System.out.println("Couldn't create zip " + dir + ".zip.");
}
for (int i = 0; i < entries.length; i++) {
f = new File(d, entries[i]);
if (f.isDirectory()) {
File cdir = f;
String[] subdirent = f.list();
for (int e = 0; e < subdirent.length; e++) {
f = new File(cdir, subdirent[e]);
try {
in = new FileInputStream(tmpdir + "/" + cdir.getName() + "/" + f.getName());
} catch (FileNotFoundException err) {
System.out.println("Couldn't open entry " + tmpdir + "/" + cdir.getName() + "/" + f.getName() + ".");
}
entry = new ZipEntry(cdir.getName() + "/" + f.getName());
try {
out.putNextEntry(entry);
} catch (IOException err) {
System.out.println("Couldn't add entry " + entry.getName() + ".");
}
try {
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
out.flush();
in.close();
} catch (IOException err) {
System.out.println("Couldn't write entry " + entry.getName() + ".");
}
}
proBar(i / rsnum);
continue;
}
try {
in = new FileInputStream(f);
} catch (FileNotFoundException err) {
System.out.println("Couldn't open entry " + f.getName() + ".");
}
entry = new ZipEntry(f.getName());
try {
out.putNextEntry(entry);
} catch (IOException err) {
System.out.println("Couldn't add entry " + entry.getName() + ".");
}
try {
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
out.flush();
in.close();
} catch (IOException err) {
System.out.println("Couldn't write entry " + entry.getName() + ".");
}
proBar(i / rsnum);
}
try {
out.close();
in.close();
} catch (IOException err) {
System.out.println("Couldn't close zip " + dir + ".zip.");
}
delDir(tmpdir);
proBar(100, "Done!");
Desktop desktop = Desktop.getDesktop();
try {
desktop.open(new File(udir + "/" + dir + ".zip"));
} catch (IOException err) {
System.out.println("Couldn't open zip " + dir + ".zip.");
}
}Example 74
| Project: SAX-master File: HeatChart.java View source code |
private void saveGraphicJpeg(BufferedImage chart, File outputFile, float quality) throws IOException {
// Setup correct compression for jpeg.
Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName("jpeg");
ImageWriter writer = (ImageWriter) iter.next();
ImageWriteParam iwp = writer.getDefaultWriteParam();
iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
iwp.setCompressionQuality(quality);
// Output the image.
FileImageOutputStream output = new FileImageOutputStream(outputFile);
writer.setOutput(output);
IIOImage image = new IIOImage(chart, null, null);
writer.write(null, image, iwp);
writer.dispose();
}Example 75
| Project: sos-dendrogram-master File: TestRunResult.java View source code |
private boolean writeImagesAsJPG(String outputDir, String filename, BufferedImage buffImage, String visName) {
outputDir = FileUtils.prepareOutputDir(outputDir);
try {
Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName("jpeg");
ImageWriter writer = iter.next();
ImageWriteParam iwp = writer.getDefaultWriteParam();
iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
// 1 specifies minimum compression and maximum quality
iwp.setCompressionQuality(1);
writer.setOutput(new FileImageOutputStream(new File(outputDir + "run_" + this.runId + "_" + filename)));
writer.write(buffImage);
} catch (IOException e) {
Logger.getLogger("at.tuwien.ifs.somtoolbox.reports").warning("Problems creating the " + visName + " for run " + this.runId + ". Reason: " + e);
return false;
}
return true;
}Example 76
| Project: folio100_frameworks_base-master File: FileIOSSpi.java View source code |
@Override
public ImageOutputStream createOutputStreamInstance(Object output, boolean useCache, File cacheDir) throws IOException {
if (output instanceof File) {
return new FileImageOutputStream((File) output);
}
throw new IllegalArgumentException("output is not instance of File");
}Example 77
| Project: WS171-frameworks-base-master File: FileIOSSpi.java View source code |
@Override
public ImageOutputStream createOutputStreamInstance(Object output, boolean useCache, File cacheDir) throws IOException {
if (output instanceof File) {
return new FileImageOutputStream((File) output);
}
throw new IllegalArgumentException("output is not instance of File");
}Example 78
| Project: geogebra-master File: MyImageIO.java View source code |
public static void write(BufferedImage img, String format, float DPI, File outFile) throws IOException {
Iterator<ImageWriter> it = ImageIO.getImageWritersByFormatName(format);
ImageWriter writer = it.next();
FileImageOutputStream fios = new FileImageOutputStream(outFile);
writer.setOutput(fios);
writeImage(writer, img, DPI);
fios.close();
}Example 79
| Project: buddycloud-media-server-master File: ImageUtils.java View source code |
private static void writeToFile(BufferedImage image, String format, File file) throws IOException {
ImageWriter writer = ImageIO.getImageWritersByFormatName(format).next();
ImageWriteParam param = getParams(writer);
writer.setOutput(new FileImageOutputStream(file));
writer.write(null, new IIOImage(image, null, null), param);
}Example 80
| Project: ceres-master File: SwappedTile.java View source code |
public void storeTile(Raster tile) throws IOException {
final ImageOutputStream stream = new FileImageOutputStream(file);
try {
writeTileData(stream, tile.getDataBuffer());
} finally {
stream.close();
}
}Example 81
| Project: proarc-master File: TiffImporter.java View source code |
private static File writeImage(BufferedImage image, File folder, String filename, ImageMimeType imageType) throws IOException {
File imgFile = new File(folder, filename);
FileImageOutputStream fos = new FileImageOutputStream(imgFile);
try {
ImageSupport.writeImageToStream(image, imageType.getDefaultFileExtension(), fos, 1.0f);
return imgFile;
} finally {
fos.close();
}
}