Java Code Examples for java.io.ByteArrayOutputStream#reset()
The following examples show how to use
java.io.ByteArrayOutputStream#reset() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BitmapUtil.java From tysq-android with GNU General Public License v3.0 | 6 votes |
/** * 压缩bitmp到目标大小(质量压缩) * * @param bitmap * @param needRecycle * @param maxSize * @return */ public static Bitmap compressBitmap(Bitmap bitmap, boolean needRecycle, long maxSize) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos); int options = 100; while (baos.toByteArray().length > maxSize) { baos.reset();//重置baos即清空baos bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos); options -= 10;//每次都减少10 } ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray()); Bitmap bm = BitmapFactory.decodeStream(isBm, null, null); if (needRecycle) { bitmap.recycle(); } bitmap = bm; return bitmap; }
Example 2
Source File: BitmapUtils.java From CrawlerForReader with Apache License 2.0 | 6 votes |
public static Bitmap compressBitmap(Bitmap image, int maxkb) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); int options = 90; image.compress(Bitmap.CompressFormat.JPEG, 90, baos);// 质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中 while (baos.toByteArray().length / 1024 > maxkb) { // 循环判断如果压缩后图片是否大于(maxkb),大于继续压缩 if (options > 10) { baos.reset();// 重置baos即清空baos options -= 10;// 每次都减少10 image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%,把压缩后的数据存放到baos中 } else { break; } } ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中 recycler(image); return BitmapFactory.decodeStream(isBm, null, null); }
Example 3
Source File: FileUtils.java From NoVIP with Apache License 2.0 | 6 votes |
/** * 将图片保存到本地时进行压缩, 即将图片从Bitmap形式变为File形式时进行压缩, * 特点是: File形式的图片确实被压缩了, 但是当你重新读取压缩后的file为 Bitmap是,它占用的内存并没有改变 * * @param bmp * @param file */ public static void compressBmpToFile(Bitmap bmp, File file) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); int options = 80;// 个人喜欢从80开始, bmp.compress(Bitmap.CompressFormat.JPEG, options, baos); while (baos.toByteArray().length / 1024 > 100) { baos.reset(); options -= 10; bmp.compress(Bitmap.CompressFormat.JPEG, options, baos); } try { FileOutputStream fos = new FileOutputStream(file); fos.write(baos.toByteArray()); fos.flush(); fos.close(); } catch (Exception e) { e.printStackTrace(); } }
Example 4
Source File: GPCrypto.java From openjavacard-tools with GNU Lesser General Public License v3.0 | 6 votes |
/** * Special padding function for SCP01 encryption * <p/> * SCP01 uses its own padding scheme where the length * of the payload is prepended. If this block is now * a multiple of the blocksize then no further padding * is applied, otherwise pad80 is used. * <p/> * @param text * @param blocksize * @return */ public static byte[] pad80_scp01(byte[] text, int blocksize) { // SCP01 has optional padding, and it will // also prepend the length to the plaintext ByteArrayOutputStream plain = new ByteArrayOutputStream(); int textLen = text.length; int totalSize = textLen + 1; plain.write(((byte) (textLen & 0xFF))); plain.write(text, 0, textLen); // check if padding required if ((totalSize % blocksize) != 0) { // perform padding (note this includes the length) byte[] padded = GPCrypto.pad80(plain.toByteArray(), blocksize); int paddedLen = padded.length; // recompose the plaintext plain.reset(); plain.write(padded, 0, paddedLen); } return plain.toByteArray(); }
Example 5
Source File: GitCommit.java From Getaviz with Apache License 2.0 | 6 votes |
private void addDiff(DiffImplementation returnable, RevCommit parent) throws IOException { RevWalk revWalk = new RevWalk(repository); parent = revWalk.parseCommit(parent.getId()); revWalk.close(); ByteArrayOutputStream put = new ByteArrayOutputStream(BUFFER_SIZE); DiffFormatter df = new DiffFormatter(put); df.setRepository(repository); df.setDiffComparator(RawTextComparator.DEFAULT); df.setDetectRenames(true); List<DiffEntry> diffs = df.scan(parent.getTree(), commit.getTree()); for(DiffEntry e : diffs){ df.format(e); String diffText = put.toString(DEFAULT_ENCODING); //TODO make encoding insertable returnable.addOperation(e.getOldPath(), new GitOperation(diffText, e.getOldPath(), e.getNewPath(), e.getChangeType())); put.reset(); } df.close(); }
Example 6
Source File: MetricsHttpServer.java From dts with Apache License 2.0 | 6 votes |
public void handle(HttpExchange t) throws IOException { String query = t.getRequestURI().getRawQuery(); ByteArrayOutputStream response = this.response.get(); response.reset(); OutputStreamWriter osw = new OutputStreamWriter(response); TextFormat.write004(osw, registry.filteredMetricFamilySamples(parseQuery(query))); osw.flush(); osw.close(); response.flush(); response.close(); t.getResponseHeaders().set("Content-Type", TextFormat.CONTENT_TYPE_004); t.getResponseHeaders().set("Content-Length", String.valueOf(response.size())); if (shouldUseCompression(t)) { t.getResponseHeaders().set("Content-Encoding", "gzip"); t.sendResponseHeaders(HttpURLConnection.HTTP_OK, 0); final GZIPOutputStream os = new GZIPOutputStream(t.getResponseBody()); response.writeTo(os); os.finish(); } else { t.sendResponseHeaders(HttpURLConnection.HTTP_OK, response.size()); response.writeTo(t.getResponseBody()); } t.close(); }
Example 7
Source File: NetworkStatsRecorder.java From android_9.0.0_r45 with Apache License 2.0 | 6 votes |
/** * Recover from {@link FileRotator} failure by dumping state to * {@link DropBoxManager} and deleting contents. */ private void recoverFromWtf() { if (DUMP_BEFORE_DELETE) { final ByteArrayOutputStream os = new ByteArrayOutputStream(); try { mRotator.dumpAll(os); } catch (IOException e) { // ignore partial contents os.reset(); } finally { IoUtils.closeQuietly(os); } mDropBox.addData(TAG_NETSTATS_DUMP, os.toByteArray(), 0); } mRotator.deleteAll(); }
Example 8
Source File: ImageUtils.java From file-service with Apache License 2.0 | 6 votes |
public static MultipartFile cutImage(MultipartFile file, Double rotate, Integer axisX, Integer axisY, Integer width, Integer height) throws java.io.IOException { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); if (rotate != null) { Thumbnails.of(file.getInputStream()).scale(1.0, 1.0).rotate(rotate).toOutputStream(outputStream); } if (axisX != null && axisY != null && width != null && height != null) { if (outputStream.size() > 0) { final InputStream rotateInputStream = new ByteArrayInputStream(outputStream.toByteArray()); outputStream.reset(); Thumbnails.of(rotateInputStream).scale(1.0, 1.0).sourceRegion(axisX, axisY, width, height).toOutputStream(outputStream); } else { Thumbnails.of(file.getInputStream()).scale(1.0, 1.0).sourceRegion(axisX, axisY, width, height).toOutputStream(outputStream); } } if (outputStream.size() > 0) { file = new MockMultipartFile(file.getName(), file.getOriginalFilename(), file.getContentType(), outputStream.toByteArray()); } return file; }
Example 9
Source File: ValidateCertPath.java From dragonwell8_jdk with GNU General Public License v2.0 | 5 votes |
private static byte[] getTotalBytes(InputStream is) throws IOException { byte[] buffer = new byte[8192]; ByteArrayOutputStream baos = new ByteArrayOutputStream(2048); int n; baos.reset(); while ((n = is.read(buffer, 0, buffer.length)) != -1) { baos.write(buffer, 0, n); } return baos.toByteArray(); }
Example 10
Source File: ImageUtils.java From AndroidWallet with GNU General Public License v3.0 | 5 votes |
public static Bitmap compressImage(Bitmap image) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); image.compress(CompressFormat.JPEG, 100, baos);//质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中 int offset = 100; while (baos.toByteArray().length / 1024 > MAX_SIZE) { //循环判断如果压缩后图片是否大于200kb,大于继续压缩 baos.reset();//重置baos即清空baos image.compress(CompressFormat.JPEG, offset, baos);//这里压缩options%,把压缩后的数据存放到baos中 offset -= 10;//每次都减少10 } ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray()); //把压缩后的数据baos存放到ByteArrayInputStream中 Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);//把ByteArrayInputStream数据生成图片 return bitmap; }
Example 11
Source File: MultiThreadReader.java From JavaInterview with Apache License 2.0 | 5 votes |
@Override public void run() { try { MappedByteBuffer mapBuffer = rAccessFile.getChannel().map(MapMode.READ_ONLY,start, this.sliceSize); ByteArrayOutputStream bos = new ByteArrayOutputStream(); for(int offset=0;offset<sliceSize;offset+=bufferSize){ int readLength; if(offset+bufferSize<=sliceSize){ readLength = bufferSize; }else{ readLength = (int) (sliceSize-offset); } mapBuffer.get(readBuff, 0, readLength); for(int i=0;i<readLength;i++){ byte tmp = readBuff[i]; if(tmp=='\n' || tmp=='\r'){ handle(bos.toByteArray()); bos.reset(); }else{ bos.write(tmp); } } } if(bos.size()>0){ handle(bos.toByteArray()); } cyclicBarrier.await();//测试性能用 }catch (Exception e) { e.printStackTrace(); } }
Example 12
Source File: AlarmManagerService.java From android_9.0.0_r45 with Apache License 2.0 | 5 votes |
private void logBatchesLocked(SimpleDateFormat sdf) { ByteArrayOutputStream bs = new ByteArrayOutputStream(2048); PrintWriter pw = new PrintWriter(bs); final long nowRTC = System.currentTimeMillis(); final long nowELAPSED = SystemClock.elapsedRealtime(); final int NZ = mAlarmBatches.size(); for (int iz = 0; iz < NZ; iz++) { Batch bz = mAlarmBatches.get(iz); pw.append("Batch "); pw.print(iz); pw.append(": "); pw.println(bz); dumpAlarmList(pw, bz.alarms, " ", nowELAPSED, nowRTC, sdf); pw.flush(); Slog.v(TAG, bs.toString()); bs.reset(); } }
Example 13
Source File: BitmapUtils.java From RecyclerViewAdapter with Apache License 2.0 | 5 votes |
public static File compressBmpToFile(Bitmap bitmap, File file, Handler handler,int what) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); int quality = 80; bitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos); while (baos.toByteArray().length / 1024 > 100 && quality > 50) { // 循环判断如果压缩后图片是否大于200kb,大于继续压缩, baos.reset(); quality -= 10; bitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos); } try { FileOutputStream fos = new FileOutputStream(file); fos.write(baos.toByteArray()); fos.flush(); fos.close(); } catch (Exception e) { e.printStackTrace(); } Message message=Message.obtain(); message.what=what; message.obj=file; handler.sendMessage(message); return file; }
Example 14
Source File: SignerOrder.java From openjdk-jdk8u with GNU General Public License v2.0 | 5 votes |
static void printSignerInfos(SignerInfo[] signerInfos) throws IOException { ByteArrayOutputStream strm = new ByteArrayOutputStream(); for (int i = 0; i < signerInfos.length; i++) { signerInfos[i].derEncode(strm); System.out.println("SignerInfo[" + i + "], length: " + strm.toByteArray().length); System.out.println(hexDump.encode(strm.toByteArray())); System.out.println("\n"); strm.reset(); } }
Example 15
Source File: TestPostHTTP.java From localization_nifi with Apache License 2.0 | 5 votes |
@Test public void testSendAsFlowFile() throws Exception { setup(null); runner.setProperty(PostHTTP.URL, server.getUrl()); runner.setProperty(PostHTTP.SEND_AS_FLOWFILE, "true"); final Map<String, String> attrs = new HashMap<>(); attrs.put("abc", "cba"); runner.enqueue("Hello".getBytes(), attrs); attrs.put("abc", "abc"); attrs.put("filename", "xyz.txt"); runner.enqueue("World".getBytes(), attrs); runner.run(1); runner.assertAllFlowFilesTransferred(PostHTTP.REL_SUCCESS); final byte[] lastPost = servlet.getLastPost(); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final ByteArrayInputStream bais = new ByteArrayInputStream(lastPost); FlowFileUnpackagerV3 unpacker = new FlowFileUnpackagerV3(); // unpack first flowfile received Map<String, String> receivedAttrs = unpacker.unpackageFlowFile(bais, baos); byte[] contentReceived = baos.toByteArray(); assertEquals("Hello", new String(contentReceived)); assertEquals("cba", receivedAttrs.get("abc")); assertTrue(unpacker.hasMoreData()); baos.reset(); receivedAttrs = unpacker.unpackageFlowFile(bais, baos); contentReceived = baos.toByteArray(); assertEquals("World", new String(contentReceived)); assertEquals("abc", receivedAttrs.get("abc")); assertEquals("xyz.txt", receivedAttrs.get("filename")); Assert.assertNull(receivedAttrs.get("Content-Length")); }
Example 16
Source File: ValidateCertPath.java From TencentKona-8 with GNU General Public License v2.0 | 5 votes |
private static byte[] getTotalBytes(InputStream is) throws IOException { byte[] buffer = new byte[8192]; ByteArrayOutputStream baos = new ByteArrayOutputStream(2048); int n; baos.reset(); while ((n = is.read(buffer, 0, buffer.length)) != -1) { baos.write(buffer, 0, n); } return baos.toByteArray(); }
Example 17
Source File: FileUtil.java From styT with Apache License 2.0 | 5 votes |
/** * 获取压缩后图片的二进制数据 * @param srcPath * @return */ public byte[] getCompressedImage(String srcPath) { if (!new File(srcPath).exists()){ return null; } BitmapFactory.Options newOpts = new BitmapFactory.Options(); //开始读入图片,此时把options.inJustDecodeBounds 设回true了 newOpts.inJustDecodeBounds = true; Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts);//此时返回bm为空 newOpts.inJustDecodeBounds = false; int w = newOpts.outWidth; int h = newOpts.outHeight; float hh = 800f;//这里设置高度为800f float ww = 480f;//这里设置宽度为480f //缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可 int be = 1;//be=1表示不缩放 if (w > h && w > ww) {//如果宽度大的话根据宽度固定大小缩放 be = (int) (newOpts.outWidth / ww); } else if (w < h && h > hh) {//如果高度高的话根据宽度固定大小缩放 be = (int) (newOpts.outHeight / hh); } if (be <= 0) { be = 1; } newOpts.inSampleSize = be;//设置缩放比例 //重新读入图片,注意此时已经把options.inJustDecodeBounds 设回false了 bitmap = BitmapFactory.decodeFile(srcPath, newOpts); ByteArrayOutputStream baos = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中 int options = 100; while (baos.toByteArray().length / 1024 > 300) { //循环判断如果压缩后图片是否大于300kb,大于继续压缩 baos.reset();//重置baos即清空baos options -= 15;//每次都减少15 bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%,把压缩后的数据存放到baos中 } return baos.toByteArray(); }
Example 18
Source File: ParseByteCacheTest.java From bcm-android with GNU General Public License v3.0 | 4 votes |
public void testTransaction(NetworkParameters params, byte[] txBytes, boolean isChild, boolean retain) throws Exception { // reference serializer to produce comparison serialization output after changes to // message structure. MessageSerializer bsRef = params.getSerializer(false); ByteArrayOutputStream bos = new ByteArrayOutputStream(); BitcoinSerializer bs = params.getSerializer(retain); Transaction t1; Transaction tRef; t1 = (Transaction) bs.deserialize(ByteBuffer.wrap(txBytes)); tRef = (Transaction) bsRef.deserialize(ByteBuffer.wrap(txBytes)); // verify our reference BitcoinSerializer produces matching byte array. bos.reset(); bsRef.serialize(tRef, bos); assertTrue(Arrays.equals(bos.toByteArray(), txBytes)); // check and retain status survive both before and after a serialization assertEquals(retain, t1.isCached()); serDeser(bs, t1, txBytes, null, null); assertEquals(retain, t1.isCached()); // compare to ref tx bos.reset(); bsRef.serialize(tRef, bos); serDeser(bs, t1, bos.toByteArray(), null, null); // retrieve a value from a child t1.getInputs(); if (t1.getInputs().size() > 0) { TransactionInput tin = t1.getInputs().get(0); assertEquals(retain, tin.isCached()); // does it still match ref tx? serDeser(bs, t1, bos.toByteArray(), null, null); } // refresh tx t1 = (Transaction) bs.deserialize(ByteBuffer.wrap(txBytes)); tRef = (Transaction) bsRef.deserialize(ByteBuffer.wrap(txBytes)); // add an input if (t1.getInputs().size() > 0) { t1.addInput(t1.getInputs().get(0)); // replicate on reference tx tRef.addInput(tRef.getInputs().get(0)); assertFalse(t1.isCached()); bos.reset(); bsRef.serialize(tRef, bos); byte[] source = bos.toByteArray(); //confirm we still match the reference tx. serDeser(bs, t1, source, null, null); } }
Example 19
Source File: CheckLogging.java From openjdk-jdk8u with GNU General Public License v2.0 | 4 votes |
/** * Check serverCallLog output */ private static void checkServerCallLog() throws Exception { ByteArrayOutputStream serverCallLog = new ByteArrayOutputStream(); RemoteServer.setLog(serverCallLog); Naming.list(LOCATION); verifyLog(serverCallLog, "list"); serverCallLog.reset(); RemoteServer.setLog(null); PrintStream callStream = RemoteServer.getLog(); if (callStream != null) { TestLibrary.bomb("call stream not null after calling " + "setLog(null)"); } else { System.err.println("call stream should be null and it is"); } Naming.list(LOCATION); if (usingOld) { if (serverCallLog.toString().indexOf("UnicastServerRef") >= 0) { TestLibrary.bomb("server call logging not turned off"); } } else if (serverCallLog.toByteArray().length != 0) { TestLibrary.bomb("call log contains output but it " + "should be empty"); } serverCallLog.reset(); RemoteServer.setLog(serverCallLog); try { // generates a notbound exception Naming.lookup(LOCATION + "notthere"); } catch (Exception e) { } verifyLog(serverCallLog, "exception"); serverCallLog.reset(); RemoteServer.setLog(serverCallLog); callStream = RemoteServer.getLog(); callStream.println("bingo, this is a getLog test"); verifyLog(serverCallLog, "bingo"); }
Example 20
Source File: FrameWrapper.java From panama with MIT License | 4 votes |
public List<byte[]> unwrapFrames(byte[] bytes) { List<byte[]> ret = new ArrayList<>(); byte[] data = new byte[unwrapBuffer.size() + bytes.length]; System.arraycopy(unwrapBuffer.toByteArray(), 0, data, 0, unwrapBuffer.size()); System.arraycopy(bytes, 0, data, unwrapBuffer.size(), bytes.length); unwrapBuffer.reset(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); int pos = 0, limit = pos + 1 + frameLength, size = data.length; while (pos < size) { byte[] buffer; switch (data[pos]) { case 0: limit = Math.min(limit + 1 + frameLength + 1, size); buffer = Arrays.copyOfRange(data, pos, limit); if (buffer.length < 1 + reservedHeaderLength) { unwrapBuffer.write(buffer, 0, buffer.length); // frame-len was truncated return ret; } int endFrameLength = KeyHelper.toBigEndianInteger(Arrays.copyOfRange(buffer, 1, 1 + reservedHeaderLength)); if (buffer.length < 1 + reservedHeaderLength + endFrameLength) { unwrapBuffer.write(buffer, 0, buffer.length); // data was truncated return ret; } else { outputStream.write(buffer, 1 + reservedHeaderLength, endFrameLength); ret.add(outputStream.toByteArray()); outputStream.reset(); pos += 1 + reservedHeaderLength + endFrameLength; limit = pos + 1 + frameLength; } break; case 1: buffer = Arrays.copyOfRange(data, pos, limit); outputStream.write(buffer, 1, buffer.length - 1); pos += 1 + frameLength; limit = Math.min(limit + 1 + frameLength, data.length); break; default: throw new RuntimeException("unknown delimiter " + data[pos]); } } return ret; }