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:Main.java

private static byte[] convertInputStreamToByteArray(InputStream inputStream) throws IOException {
    byte[] bytes = null;
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    byte data[] = new byte[1024];
    int count;/*from   www  . j a  v a  2s  .  c  o m*/
    while ((count = inputStream.read(data)) != -1) {
        bos.write(data, 0, count);
    }
    bos.flush();
    bos.close();
    inputStream.close();
    bytes = bos.toByteArray();
    return bytes;
}

From source file:Main.java

public static byte[] loadImageDataFromWeb(String url) {

    byte[] imageData = null;
    try {/*from w  w  w.j a  v a2s .c o  m*/

        URLConnection connection = new URL(url).openConnection();
        InputStream stream = connection.getInputStream();
        //BufferedInputStream in=new BufferedInputStream(stream);//default 8k buffer
        BufferedInputStream in = new BufferedInputStream(stream, 10240);//YG: 10k=10240, 2x8k=16384
        ByteArrayOutputStream out = new ByteArrayOutputStream(10240);
        int read;
        byte[] b = new byte[4096];

        while ((read = in.read(b)) != -1) {
            out.write(b, 0, read);
        }

        out.flush();
        out.close();

        imageData = out.toByteArray();

    } catch (Exception e) {

        Log.w(TAG, "Exc=" + e);
        return null;
    }

    return imageData;
}

From source file:Main.java

public static byte[] compressToBytes(Bitmap bitmap, int quality) {
    ByteArrayOutputStream baos = null;
    try {//from  w w  w  .java  2  s.co m
        baos = new ByteArrayOutputStream(65536);
        bitmap.compress(CompressFormat.PNG, quality, baos);
        return baos.toByteArray();
    } finally {
        try {
            baos.flush();
            baos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:Main.java

public static byte[] getByteFromInputStream(final InputStream in) throws IOException {
    ByteArrayOutputStream buffer = null;
    buffer = new ByteArrayOutputStream();
    int nRead;//from  w  ww.ja va  2  s  . c  o  m
    final byte[] data = new byte[16384];

    while ((nRead = in.read(data, 0, data.length)) != -1) {
        buffer.write(data, 0, nRead);
    }

    buffer.flush();

    return buffer.toByteArray();
}

From source file:com.android.contacts.util.ContactPhotoUtils.java

/**
 * Creates a byte[] containing the PNG-compressed bitmap, or null if
 * something goes wrong./* w  w  w .  ja  v a  2  s  . c o  m*/
 */
public static byte[] compressBitmap(Bitmap bitmap) {
    final int size = bitmap.getWidth() * bitmap.getHeight() * 4;
    final ByteArrayOutputStream out = new ByteArrayOutputStream(size);
    try {
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
        out.flush();
        out.close();
        return out.toByteArray();
    } catch (IOException e) {
        Log.w(TAG, "Unable to serialize photo: " + e.toString());
        return null;
    }
}

From source file:Main.java

/**
 * Download the avatar image from the server.
 *
 * @param avatarUrl the URL pointing to the avatar image
 * @return a byte array with the raw JPEG avatar image
 *///from  www .jav  a 2 s.c o m
public static byte[] downloadAvatar(final String avatarUrl) {
    // If there is no avatar, we're done
    if (TextUtils.isEmpty(avatarUrl)) {
        return null;
    }

    try {
        Log.i(TAG, "Downloading avatar: " + avatarUrl);
        // Request the avatar image from the server, and create a bitmap
        // object from the stream we get back.
        URL url = new URL(avatarUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.connect();
        try {
            final BitmapFactory.Options options = new BitmapFactory.Options();
            final Bitmap avatar = BitmapFactory.decodeStream(connection.getInputStream(), null, options);

            // Take the image we received from the server, whatever format it
            // happens to be in, and convert it to a JPEG image. Note: we're
            // not resizing the avatar - we assume that the image we get from
            // the server is a reasonable size...
            Log.i(TAG, "Converting avatar to JPEG");
            ByteArrayOutputStream convertStream = new ByteArrayOutputStream(
                    avatar.getWidth() * avatar.getHeight() * 4);
            avatar.compress(Bitmap.CompressFormat.JPEG, 95, convertStream);
            convertStream.flush();
            convertStream.close();
            // On pre-Honeycomb systems, it's important to call recycle on bitmaps
            avatar.recycle();
            return convertStream.toByteArray();
        } finally {
            connection.disconnect();
        }
    } catch (MalformedURLException muex) {
        // A bad URL - nothing we can really do about it here...
        Log.e(TAG, "Malformed avatar URL: " + avatarUrl);
    } catch (IOException ioex) {
        // If we're unable to download the avatar, it's a bummer but not the
        // end of the world. We'll try to get it next time we sync.
        Log.e(TAG, "Failed to download user avatar: " + avatarUrl);
    }
    return null;
}

From source file:com.openkm.util.ImageUtils.java

/**
 * crop/*  www  .ja v a 2  s.  co  m*/
 */
public static byte[] crop(byte[] img, int x, int y, int width, int height) throws RuntimeException {
    log.debug("crop({}, {}, {}, {}, {})", new Object[] { img.length, x, y, width, height });
    ByteArrayInputStream bais = new ByteArrayInputStream(img);
    byte[] imageInByte;

    try {
        BufferedImage image = ImageIO.read(bais);
        BufferedImage croppedImage = image.getSubimage(x, y, width, height);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(croppedImage, "png", baos);
        baos.flush();
        imageInByte = baos.toByteArray();
        IOUtils.closeQuietly(baos);
    } catch (IOException e) {
        log.error(e.getMessage());
        throw new RuntimeException("IOException: " + e.getMessage(), e);
    } finally {
        IOUtils.closeQuietly(bais);
    }

    log.debug("crop: {}", imageInByte.length);
    return imageInByte;
}

From source file:Main.java

public static byte[] readStream(InputStream inStream) {
    try {//from  w  w  w. j av a  2 s.  c  o  m
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }

        byte[] data = outStream.toByteArray();
        outStream.flush();
        outStream.close();
        inStream.close();

        return data;
    } catch (OutOfMemoryError e) {
        return null;
    } catch (Exception e) {
        return null;
    }
}

From source file:com.bigdata.rockstor.console.RockStorSender.java

private static HttpResp buildHttpResponse(HttpResponse response) {
    HttpResp resp = new HttpResp();
    resp.setStatus(response.getStatusLine().getStatusCode());
    Map<String, String> head = new HashMap<String, String>();
    for (Header header : response.getAllHeaders()) {
        head.put(header.getName(), header.getValue());
    }//ww  w  .  j av  a2 s .c  om
    resp.setHead(head);

    if ("chunked".equals(head.get("Transfer-Encoding"))
            || (head.containsKey("Content-Length") && !head.get("Content-Length").equals("0"))) {
        try {
            InputStream is = response.getEntity().getContent();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int len = 0;
            byte[] b = new byte[4096];
            while ((len = is.read(b)) > 0) {
                baos.write(b, 0, len);
            }
            baos.flush();
            resp.setBody(new String(baos.toByteArray()));
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NullPointerException e) {
            // HEAD ?
        }
    }
    return resp;
}

From source file:com.giacomodrago.immediatecrypt.messagecipher.Compression.java

public static byte[] decompress(byte[] plaintext) {
    try {/*from  w  ww .  j a va  2s.c  o  m*/
        ByteArrayOutputStream writer = new ByteArrayOutputStream();
        ByteArrayInputStream reader = new ByteArrayInputStream(plaintext);
        GZIPInputStream gzipStream = new GZIPInputStream(reader);
        IOUtils.copy(gzipStream, writer);
        gzipStream.close();
        writer.flush();
        writer.close();
        return writer.toByteArray();
    } catch (IOException ex) {
        return null; // Invalid source data
    }
}