Example usage for java.io ByteArrayOutputStream flush

List of usage examples for java.io ByteArrayOutputStream flush

Introduction

In this page you can find the example usage for java.io ByteArrayOutputStream flush.

Prototype

public void flush() throws IOException 

Source Link

Document

Flushes this output stream and forces any buffered output bytes to be written out.

Usage

From source file:com.itextpdf.text.pdf.pdfcleanup.PdfCleanUpRenderListener.java

private byte[] getJPGBytes(BufferedImage image) {
    ByteArrayOutputStream outputStream = null;

    try {//  www . ja v  a2 s .  co m
        ImageWriter jpgWriter = ImageIO.getImageWritersByFormatName("jpg").next();
        ImageWriteParam jpgWriteParam = jpgWriter.getDefaultWriteParam();
        jpgWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        jpgWriteParam.setCompressionQuality(1.0f);

        outputStream = new ByteArrayOutputStream();
        jpgWriter.setOutput(new MemoryCacheImageOutputStream((outputStream)));
        IIOImage outputImage = new IIOImage(image, null, null);

        jpgWriter.write(null, outputImage, jpgWriteParam);
        jpgWriter.dispose();
        outputStream.flush();

        return outputStream.toByteArray();
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        closeOutputStream(outputStream);
    }
}

From source file:net.cbtltd.server.UploadFileService.java

private static boolean getImage(String fn, BufferedImage image, Map<String, byte[]> images) {
    int fullsizepixels = Text.FULLSIZE_PIXELS_VALUE;
    int thumbnailpixels = Text.THUMBNAIL_PIXELS_VALUE;
    //      ByteBuffer byteArray = new ByteBuffer();
    ByteArrayOutputStream bOutputReg = new ByteArrayOutputStream();
    ByteArrayOutputStream bOutputThumb = new ByteArrayOutputStream();
    ImageIcon imageIcon = new ImageIcon(image);
    //      if(image.getIconHeight() > 0 && image.getIconWidth() > 0) {
    if (imageIcon.getImageLoadStatus() == MediaTracker.COMPLETE) {
        ImageIcon fullsizeImage = new ImageIcon(
                imageIcon.getImage().getScaledInstance(-1, fullsizepixels, Image.SCALE_SMOOTH));
        LOG.debug("\n UploadFileService setImage image= " + imageIcon + " width=" + fullsizeImage.getIconWidth()
                + "  height=" + fullsizeImage.getIconHeight());
        BufferedImage fullsizeBufferedImage = new BufferedImage(fullsizeImage.getIconWidth(),
                fullsizeImage.getIconHeight(), BufferedImage.TYPE_INT_RGB);
        Graphics fullsizeGraphics = fullsizeBufferedImage.getGraphics();
        fullsizeGraphics.drawImage(fullsizeImage.getImage(), 0, 0, null);
        String fullsizeFile = fn.substring(0, fn.lastIndexOf('.')) + ".jpg";

        try {/* w w w . j a v  a 2s .  c  o  m*/
            ImageIO.write(fullsizeBufferedImage, FULLSIZE_JPEG, bOutputReg);
            bOutputReg.flush();
            images.put(fullsizeFile, bOutputReg.toByteArray());
            bOutputReg.close();
        } catch (IOException x) {
            throw new RuntimeException("Error saving full sized image " + x.getMessage());
        } catch (Exception e) {
            LOG.error(e.getMessage() + " Error saving full sized image: " + fullsizeFile);
        }

        ImageIcon thumbnailImage = new ImageIcon(
                imageIcon.getImage().getScaledInstance(-1, thumbnailpixels, Image.SCALE_SMOOTH));
        String thumbnailFile = fn.substring(0, fn.lastIndexOf('.')) + "Thumb.jpg";

        BufferedImage thumbnailBufferedImage = new BufferedImage(thumbnailImage.getIconWidth(),
                thumbnailImage.getIconHeight(), BufferedImage.TYPE_INT_RGB);
        Graphics thumbnailGraphics = thumbnailBufferedImage.getGraphics();
        thumbnailGraphics.drawImage(thumbnailImage.getImage(), 0, 0, null);
        try {
            ImageIO.write(thumbnailBufferedImage, FULLSIZE_JPEG, bOutputThumb);
            bOutputThumb.flush();
            images.put(thumbnailFile, bOutputThumb.toByteArray());
            bOutputThumb.close();
        } catch (IOException x) {
            throw new RuntimeException("Error saving thumbnail image " + x.getMessage());
        } catch (Exception e) {
            LOG.error(e.getMessage() + " Error saving thumbnail image: " + thumbnailFile);
        }

        return true;
    } else {
        LOG.error("\n UploadFileService setImage image= " + imageIcon + " width=" + imageIcon.getIconWidth()
                + "  height=" + imageIcon.getIconHeight());
        return false;
    }
}

From source file:com.amalto.core.storage.StorageWrapper.java

@Override
public List<String> globalSearch(String dataCluster, String keyword, int start, int end)
        throws XmlServerException {
    Storage storage = getStorage(dataCluster);
    MetadataRepository repository = storage.getMetadataRepository();
    Iterator<ComplexTypeMetadata> types = repository.getUserComplexTypes().iterator();
    if (types.hasNext()) {
        ComplexTypeMetadata mainType = types.next();
        while (types.hasNext() && mainType.getKeyFields().size() > 1) {
            ComplexTypeMetadata next = types.next();
            if (next.getKeyFields().size() > 1) {
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("Ignoring type '" + next.getName() + "' (compound key)."); //$NON-NLS-1$ //$NON-NLS-2$
                }// w  w w.j a  va 2 s  .co  m
            }
            mainType = next;
        }
        UserQueryBuilder qb = from(mainType);
        while (types.hasNext()) {
            ComplexTypeMetadata additionalType = types.next();
            if (additionalType.getKeyFields().size() == 1) {
                qb.and(additionalType);
            } else {
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("Ignoring type '" + additionalType.getName() + "' (compound key)."); //$NON-NLS-1$ //$NON-NLS-2$
                }
            }
        }
        qb.where(fullText(keyword));
        qb.start(start);
        qb.limit(end);
        StorageResults results = null;
        try {
            storage.begin();
            results = Split.fetchAndMerge(storage, qb.getSelect()); // TMDM-7290: Split main query into smaller queries.
            DataRecordWriter writer = new FullTextResultsWriter(keyword);
            List<String> resultsAsXmlStrings = new ArrayList<String>(results.getCount() + 1);
            resultsAsXmlStrings.add(String.valueOf(results.getCount()));
            for (DataRecord result : results) {
                ByteArrayOutputStream output = new ByteArrayOutputStream();
                writer.write(result, output);
                output.flush();
                resultsAsXmlStrings.add(output.toString());
            }
            storage.commit();
            return resultsAsXmlStrings;
        } catch (Exception e) {
            storage.rollback();
            throw new XmlServerException(e);
        } finally {
            if (results != null) {
                results.close();
            }
        }
    } else {
        return Collections.emptyList();
    }
}

From source file:com.apporiented.hermesftp.server.impl.ServerRFC959Test.java

private byte[] createBlockData() throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    baos.write(0);//from   w  w  w.  jav a  2s .co m
    baos.write(0);
    baos.write(1);
    int len = 1;
    for (int i = 0; i < len; i++) {
        baos.write((byte) 0xC1);
    }
    baos.write(BlockModeConstants.DESC_CODE_EOR);
    baos.write(0);
    baos.write(3);
    len = 3;
    for (int i = 0; i < len; i++) {
        baos.write((byte) 0xC2);
    }
    baos.write(BlockModeConstants.DESC_CODE_REST);
    baos.write(0);
    baos.write(1);
    baos.write(5);

    baos.write(BlockModeConstants.DESC_CODE_EOR | BlockModeConstants.DESC_CODE_EOF);
    baos.write(1);
    baos.write(2);
    len = (1 << 8) + 2;
    for (int i = 0; i < len; i++) {
        baos.write((byte) 0xC3);
    }
    baos.flush();
    baos.close();

    return baos.toByteArray();
}

From source file:com.consol.citrus.report.HtmlReporter.java

/**
 * Reads citrus logo png image and converts to base64 encoded string for inline HTML image display.
 * @return/*from  w w  w . ja  v  a 2s .  c  om*/
 * @throws IOException 
 */
private String getLogoImageData() {
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    BufferedInputStream reader = null;

    try {
        reader = new BufferedInputStream(logo.getInputStream());

        byte[] contents = new byte[1024];
        while (reader.read(contents) != -1) {
            os.write(contents);
        }
    } catch (IOException e) {
        log.warn("Failed to add logo image data to HTML report", e);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException ex) {
                log.warn("Failed to close logo image resource for HTML report", ex);
            }
        }

        try {
            os.flush();
        } catch (IOException ex) {
            log.warn("Failed to flush logo image stream for HTML report", ex);
        }
    }

    return Base64.encodeBase64String(os.toByteArray());
}

From source file:io.selendroid.server.model.DefaultSelendroidDriver.java

@Override
@SuppressWarnings("deprecation")
public byte[] takeScreenshot() {
    ViewHierarchyAnalyzer viewAnalyzer = ViewHierarchyAnalyzer.getDefaultInstance();

    // TODO ddary review later, but with getRecentDecorView() it seems to work better
    // long drawingTime = 0;
    // View container = null;
    // for (View view : viewAnalyzer.getTopLevelViews()) {
    // if (view != null && view.isShown() && view.hasWindowFocus()
    // && view.getDrawingTime() > drawingTime) {
    // container = view;
    // drawingTime = view.getDrawingTime();
    // }/*w  ww .  ja va  2  s .c o  m*/
    // }
    // final View mainView = container;
    final View mainView = viewAnalyzer.getRecentDecorView();
    if (mainView == null) {
        throw new SelendroidException("No open windows.");
    }
    done = false;
    long end = System.currentTimeMillis() + serverInstrumentation.getAndroidWait().getTimeoutInMillis();
    final byte[][] rawPng = new byte[1][1];
    ServerInstrumentation.getInstance().getCurrentActivity().runOnUiThread(new Runnable() {
        public void run() {
            synchronized (syncObject) {
                Display display = serverInstrumentation.getCurrentActivity().getWindowManager()
                        .getDefaultDisplay();
                Point size = new Point();
                try {
                    display.getSize(size);
                } catch (NoSuchMethodError ignore) { // Older than api level 13
                    size.x = display.getWidth();
                    size.y = display.getHeight();
                }

                // Get root view
                View view = mainView.getRootView();

                // Create the bitmap to use to draw the screenshot
                final Bitmap bitmap = Bitmap.createBitmap(size.x, size.y, Bitmap.Config.ARGB_8888);
                final Canvas canvas = new Canvas(bitmap);

                // Get current theme to know which background to use
                final Activity activity = serverInstrumentation.getCurrentActivity();
                final Theme theme = activity.getTheme();
                final TypedArray ta = theme
                        .obtainStyledAttributes(new int[] { android.R.attr.windowBackground });
                final int res = ta.getResourceId(0, 0);
                final Drawable background = activity.getResources().getDrawable(res);

                // Draw background
                background.draw(canvas);

                // Draw views
                view.draw(canvas);

                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                if (!bitmap.compress(Bitmap.CompressFormat.PNG, 70, stream)) {
                    throw new RuntimeException("Error while compressing screenshot image.");
                }
                try {
                    stream.flush();
                    stream.close();
                } catch (IOException e) {
                    throw new RuntimeException("I/O Error while capturing screenshot: " + e.getMessage());
                } finally {
                    Closeable closeable = (Closeable) stream;
                    try {
                        if (closeable != null) {
                            closeable.close();
                        }
                    } catch (IOException ioe) {
                        // ignore
                    }
                }
                rawPng[0] = stream.toByteArray();
                mainView.destroyDrawingCache();
                done = true;
                syncObject.notify();
            }
        }
    });

    waitForDone(end, serverInstrumentation.getAndroidWait().getTimeoutInMillis(), "Failed to take screenshot.");
    return rawPng[0];
}

From source file:com.lehman.ic9.net.httpClient.java

/**
 * Called from perform request method to get the result content
 * as a byte array./*  w w  w . j a  va2  s . com*/
 * @param is an InputStream object with the stream of the response.
 * @return A byte[] with the result content.
 * @throws IOException Exception
 * @throws ic9exception Exception
 */
private byte[] getContentBinary(InputStream is) throws IOException, ic9exception {
    byte[] ret = null;
    int read = -1;
    byte buff[] = new byte[1024];
    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    while ((read = is.read(buff)) != -1) {
        bos.write(buff, 0, read);
    }
    bos.flush();
    ret = bos.toByteArray();
    bos.close();

    return ret;
}

From source file:com.jafme.mobile.activity.CropImageActivity.java

private void uploadImage(Bitmap croppedBitmap) {

    if (!needUpload) {

        final File file = new File(getCacheDir(), "wizard_avatar");
        final Uri fileUri = Uri.fromFile(file);
        OutputStream fileOutputStream = null;
        try {//from   w w  w.j  a  v  a  2  s.  c o m
            fileOutputStream = getContentResolver().openOutputStream(fileUri);
            if (fileOutputStream == null)
                throw new IOException("Can't open output stream");
            if (croppedBitmap.compress(Bitmap.CompressFormat.JPEG, 90, fileOutputStream)) {
                fileOutputStream.flush();

                final Photo photo = new Photo(-1, fileUri.toString());
                setResultPhoto(photo, -1);

            }
        } catch (IOException e) {
            setResultException(e);
        } finally {
            CropUtil.closeSilently(fileOutputStream);
        }

    } else {

        long startTime = System.currentTimeMillis();

        ByteArrayOutputStream baos = null;
        try {

            // ??   JPG  baos
            baos = new ByteArrayOutputStream();
            if (!croppedBitmap.compress(Bitmap.CompressFormat.JPEG, 90, baos)) {
                throw new IOException("Can't compress photo");
            }
            baos.flush();

            // encod  base64
            final byte[] encodedJpgImage = Base64.encode(baos.toByteArray(), Base64.DEFAULT);
            final String base64Photo = new String(encodedJpgImage, "UTF-8");

            /*
            try {
               FileWriter fileWriter = new FileWriter(new File(getExternalFilesDir(null), "photo.base64"));
               fileWriter.write(base64Photo);
               fileWriter.close();
            } catch (IOException e) {
               e.printStackTrace();
            }
            */

            // ?   ?
            final JsonObject jsonRequest = new JsonObject();
            jsonRequest.addProperty("image_string", base64Photo);
            jsonRequest.addProperty("image_extension", "jpg");

            final ApiRest api = Api.getInstance(this);

            long vacancyId = 0;
            Response response;
            Photo photo;
            switch (type) {
            case TYPE_APPLICANT_PHOTO:
                response = api.uploadApplicantPhoto(jsonRequest);
                photo = Network.responseToObject(response, Photo.class, false);
                break;

            case TYPE_USER_AVATAR:
                response = api.uploadUserAvatar(jsonRequest);
                if (response == null)
                    throw new IOException("No response received");
                final int statusCode = response.getStatus();
                if (statusCode < 200 || statusCode >= 300)
                    throw new IOException(response.getReason());

                // HTTP 204 No content -   ? GET /user/avatar
                response = api.getUserAvatar();
                @SuppressWarnings("unchecked")
                Map<String, String> paths = Network.responseToObject(response, HashMap.class, false);
                photo = new Photo(paths);
                break;

            case TYPE_VACANCY_PHOTO:
                vacancyId = args != null ? args.getLong(ARG_VACANCY_ID, -1) : -1;
                boolean isPrimary = args != null && args.getBoolean(ARG_IS_PRIMARY);

                if (vacancyId == -1) {
                    // ? ?  ?

                    JsonObject jsonRequest2 = new JsonObject();
                    jsonRequest2.addProperty("position", getString(R.string.new_vacancy));

                    response = api.createEmployerVacancy(jsonRequest2);
                    Vacancy newVacancy = Network.responseToObject(response, Vacancy.class, false);

                    vacancyId = newVacancy.id;
                }

                jsonRequest.addProperty("is_primary", isPrimary);
                response = api.uploadVacancyPhoto(vacancyId, jsonRequest);
                photo = Network.responseToObject(response, Photo.class, false);

                break;

            default:
                throw new RuntimeException("Invalid photo type specified: " + type);
            }

            setResultPhoto(photo, vacancyId);

            long uploadTime = System.currentTimeMillis() - startTime;

            final Tracker tracker = ((JafmeApp) getApplication()).getDefaultTracker();
            tracker.send(new HitBuilders.TimingBuilder().setCategory("UX").setValue(uploadTime)
                    .setVariable("Photo upload").setLabel("Type: " + type).build());

        } catch (IOException | RetrofitError e) {
            e.printStackTrace();
            setResultException(e);
        } finally {
            CropUtil.closeSilently(baos);
        }

    }

    if (removeOriginal && "file".equals(sourceUri.getScheme())) {
        File file = new File(sourceUri.getPath());
        if (!file.delete()) {
            file.deleteOnExit();
        }
    }

    // ? bitmap  ?
    final Bitmap b = croppedBitmap;
    handler.post(new Runnable() {
        public void run() {
            imageView.clear();
            b.recycle();
        }
    });

    finish();
}

From source file:net.filterlogic.util.imaging.ToTIFF.java

/**
 * // w ww.  j  a va  2 s. co m
 * @param fileName
 */
public void test6(String fileName) {
    try {
        File f = new File(fileName);

        ImageInputStream imageInputStream = ImageIO.createImageInputStream(f);
        java.util.Iterator readers = ImageIO.getImageReaders(imageInputStream);
        ImageReader reader1 = (ImageReader) readers.next();
        ImageInputStream iis = ImageIO.createImageInputStream(new FileInputStream(f));
        reader1.setInput(iis);

        int number = reader1.getNumImages(true);
        Iterator writers = ImageIO.getImageWritersByFormatName("tiff");
        ImageWriter writer = (ImageWriter) writers.next();

        ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
        ImageOutputStream ios = null;
        BufferedImage img = null;

        for (int i = 0; i < number; i++) {
            img = reader1.read(i);
            ios = ImageIO.createImageOutputStream(byteOut);
            writer.setOutput(ios);
            writer.write(img);
            ios.flush();
            img.flush();
            byteOut.flush();
        }

    } catch (Exception e) {
        System.out.println(e.toString());
    }

}