public ActionForward createClassifications( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws FenixFilterException, FenixServiceException, IOException { IUserView userView = UserView.getUser(); DynaActionForm dynaActionForm = (DynaActionForm) form; Integer degreeCurricularPlanID = (Integer) dynaActionForm.get("degreeCurricularPlanID"); Integer[] entryGradeLimits = (Integer[]) dynaActionForm.get("entryGradeLimits"); Integer[] approvationRatioLimits = (Integer[]) dynaActionForm.get("approvationRatioLimits"); Integer[] arithmeticMeanLimits = (Integer[]) dynaActionForm.get("arithmeticMeanLimits"); Object[] args = { entryGradeLimits, approvationRatioLimits, arithmeticMeanLimits, degreeCurricularPlanID }; ByteArrayOutputStream resultStream = (ByteArrayOutputStream) ServiceUtils.executeService("CreateClassificationsForStudents", args); String currentDate = new SimpleDateFormat("dd-MMM-yy.HH-mm").format(new Date()); response.setHeader( "Content-disposition", "attachment;filename=" + degreeCurricularPlanID + "_" + currentDate + ".zip"); response.setContentType("application/zip"); DataOutputStream dos = new DataOutputStream(response.getOutputStream()); dos.write(resultStream.toByteArray()); dos.close(); return null; }
public void sendSupportedChannels() { if (getHandle().field_71135_a == null) return; Set<String> listening = server.getMessenger().getIncomingChannels(); if (!listening.isEmpty()) { net.minecraft.network.packet.Packet250CustomPayload packet = new net.minecraft.network.packet.Packet250CustomPayload(); packet.field_73630_a = "REGISTER"; ByteArrayOutputStream stream = new ByteArrayOutputStream(); for (String channel : listening) { try { stream.write(channel.getBytes("UTF8")); stream.write((byte) 0); } catch (IOException ex) { Logger.getLogger(CraftPlayer.class.getName()) .log(Level.SEVERE, "Could not send Plugin Channel REGISTER to " + getName(), ex); } } packet.field_73629_c = stream.toByteArray(); packet.field_73628_b = packet.field_73629_c.length; getHandle().field_71135_a.func_72567_b(packet); } }
public static void downloadIt() { URL website; try { website = new URL(MainConstants.SOURCES_URL); try { InputStream in = new BufferedInputStream(website.openStream()); ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buf = new byte[1024]; int n = 0; while (-1 != (n = in.read(buf))) { out.write(buf, 0, n); } out.close(); in.close(); byte[] response = out.toByteArray(); FileOutputStream fos = new FileOutputStream(MainConstants.INPUT_ZIP_FILE); fos.write(response); fos.close(); System.out.println("Download finished."); } catch (IOException ce) { System.out.print("Connection problem : " + ce); } } catch (MalformedURLException e) { e.printStackTrace(); } }
private static String receiveResponseString(BufferedInputStream in, String contentType) throws Exception { String fullResponse = null; ByteArrayOutputStream bos = new ByteArrayOutputStream(1024); byte[] arr = new byte[1024]; int numread = 0; while ((numread = in.read(arr)) != -1) { bos.write(arr, 0, numread); } final String CHARSET = "charset="; String charset = null; int charsetInd = contentType.indexOf(CHARSET); if (charsetInd != -1) { charset = contentType.substring(charsetInd + CHARSET.length()); } if (charset == null) { fullResponse = bos.toString(); } else { fullResponse = bos.toString(charset); } return fullResponse; }
public void processImage(String fileName) throws IOException { if (fileName.startsWith("/")) { throw new IllegalArgumentException(); } final SourceStringReader sourceStringReader = new SourceStringReader(incoming.get(fileName)); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final FileFormat format = FileFormat.PNG; final DiagramDescription desc = sourceStringReader.generateDiagramDescription(baos, new FileFormatOption(format)); final String pngFileName = format.changeName(fileName, 0); final String errorFileName = pngFileName.substring(0, pngFileName.length() - 4) + ".err"; synchronized (this) { outgoing.remove(pngFileName); outgoing.remove(errorFileName); if (desc != null && desc.getDescription() != null) { outgoing.put(pngFileName, baos.toByteArray()); if (desc.getDescription().startsWith("(Error)")) { final ByteArrayOutputStream errBaos = new ByteArrayOutputStream(); sourceStringReader.generateImage(errBaos, new FileFormatOption(FileFormat.ATXT)); errBaos.close(); outgoing.put(errorFileName, errBaos.toByteArray()); } } } }
public static BinaryData createBinaryData(final FileItem fileItem, final String label) throws VerticalAdminException { BinaryData binaryData = new BinaryData(); InputStream fis = null; try { binaryData.fileName = FileUtil.getFileName(fileItem); fis = fileItem.getInputStream(); ByteArrayOutputStream bao = new ByteArrayOutputStream(); byte[] buf = new byte[1024 * 10]; int size; while ((size = fis.read(buf)) > 0) { bao.write(buf, 0, size); } binaryData.data = bao.toByteArray(); binaryData.label = label; } catch (IOException e) { VerticalAdminLogger.errorAdmin(AdminHandlerBaseServlet.class, 20, "I/O error: %t", e); } finally { try { if (fis != null) { fis.close(); } } catch (IOException ioe) { String message = "Failed to close file input stream: %t"; VerticalAdminLogger.warn(AdminHandlerBaseServlet.class, 0, message, ioe); } } return binaryData; }
/** * compare the byte-array representation of two TaskObjects. * * @param f TaskObject * @param s TaskObject * @return true if the two arguments have the same byte-array */ private boolean sameBytes(TaskObject f, TaskObject s) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutput out = null; try { out = new ObjectOutputStream(bos); out.writeObject(f); byte[] fs = bos.toByteArray(); out.writeObject(s); byte[] ss = bos.toByteArray(); if (fs.length != ss.length) return false; for (int i = 0; i < fs.length; i++) { if (fs[i] != ss[i]) return false; } return true; } catch (IOException e) { e.printStackTrace(); return false; } finally { if (out != null) { try { out.close(); } catch (IOException e) { // ignore } try { bos.close(); } catch (IOException e) { // ignore } } } }
private static void writeStaticAssets(AssetManager assets, ZipOutputStream out, String path) { try { for (String item : assets.list(path)) { try { InputStream fileIn = assets.open(path + "/" + item); ByteArrayOutputStream baos = new ByteArrayOutputStream(); BufferedInputStream bin = new BufferedInputStream(fileIn); byte[] buffer = new byte[8192]; int read = 0; while ((read = bin.read(buffer, 0, buffer.length)) != -1) { baos.write(buffer, 0, read); } bin.close(); baos.close(); ZipEntry entry = new ZipEntry(path + "/" + item); out.putNextEntry(entry); out.write(baos.toByteArray()); out.closeEntry(); } catch (IOException e) { BootstrapSiteExporter.writeStaticAssets(assets, out, path + "/" + item); } } } catch (IOException e) { e.printStackTrace(); } }
/** * Handles the write serialization of the Package. Patterns in Rules may reference generated data * which cannot be serialized by default methods. The Package uses PackageCompilationData to hold * a reference to the generated bytecode. The generated bytecode must be restored before any * Rules. * * @param stream out the stream to write the object to; should be an instance of * DroolsObjectOutputStream or OutputStream */ public void writeExternal(ObjectOutput stream) throws IOException { boolean isDroolsStream = stream instanceof DroolsObjectOutputStream; ByteArrayOutputStream bytes = null; ObjectOutput out; if (isDroolsStream) { out = stream; } else { bytes = new ByteArrayOutputStream(); out = new DroolsObjectOutputStream(bytes); } out.writeObject(this.dialectRuntimeRegistry); out.writeObject(this.typeDeclarations); out.writeObject(this.name); out.writeObject(this.imports); out.writeObject(this.staticImports); out.writeObject(this.functions); out.writeObject(this.accumulateFunctions); out.writeObject(this.factTemplates); out.writeObject(this.ruleFlows); out.writeObject(this.globals); out.writeBoolean(this.valid); out.writeBoolean(this.needStreamMode); out.writeObject(this.rules); out.writeObject(this.classFieldAccessorStore); out.writeObject(this.entryPointsIds); out.writeObject(this.windowDeclarations); out.writeObject(this.traitRegistry); // writing the whole stream as a byte array if (!isDroolsStream) { bytes.flush(); bytes.close(); stream.writeObject(bytes.toByteArray()); } }
/** * Processes MathML data. * * @param element MathML data element * @param block parent block * @throws DocumentException if some error occurs */ private void processMath(Element element, Block<Atom> block) throws DocumentException { try { element.setAttribute("xmlns:m", URI_M); element.setAttribute("xmlns:w", URI_W); ByteArrayOutputStream omml = new ByteArrayOutputStream(); DomUtil.save(element, omml); Source xsl = new StreamSource(getClass().getResourceAsStream(XSL_OMML2MML)); Source xml = new StreamSource(new ByteArrayInputStream(omml.toByteArray())); DOMResult mml = new DOMResult(); XslUtil.transform(xml, xsl, mml); LayoutContextImpl context = new LayoutContextImpl(LayoutContextImpl.getDefaultLayoutContext()); Float fontSize = (Float) context.getParameter(Parameter.MATHSIZE); final float factor = 1.5F; context.setParameter(Parameter.MATHSIZE, factor * fontSize); context.setParameter(Parameter.MFRAC_KEEP_SCRIPTLEVEL, Boolean.FALSE); ByteArrayOutputStream out = new ByteArrayOutputStream(); ConverterRegistry.getInstance() .getConverter("image/png") .convert(mml.getNode(), context, out); Image image = new Image(); mathImageIndex++; final String imageName = "mml-" + mathImageIndex + ".png"; image.setUrl(imageName); image.setAlt(imageName); image.setData(out.toByteArray()); block.add(image); } catch (XmlException e) { throw new DocumentException(e); } catch (IOException e) { throw new DocumentException(e); } }
public void onPictureTaken(byte[] data, Camera arg1) { if (data != null) { PictureTaken = true; // Extract the bitmap from data Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length); // Only select the region we want bitmap = ThumbnailUtils.extractThumbnail( bitmap, bitmap.getWidth() / 9, bitmap.getHeight() / 3); // Rotate the bitmap Matrix matrix = new Matrix(); matrix.postRotate(90); bitmap = Bitmap.createBitmap( bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true); // Convert it back to byte array data ByteArrayOutputStream stream = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream); byte[] bmArray = stream.toByteArray(); // Get the underlying pixel bytes array image = bmArray; if (image != null) { Toast.makeText(getActivity(), "Photo Taken", Toast.LENGTH_SHORT).show(); } } cameraObject.startPreview(); }
@Test public void validateJsonSerialization() throws IOException { final JsonSerializer serializer = new JsonSerializer(); Record record = new StandardRecord("cisco"); record.setId("firewall_record1"); record.setField("timestamp", FieldType.LONG, new Date().getTime()); record.setField("method", FieldType.STRING, "GET"); record.setField("ip_source", FieldType.STRING, "123.34.45.123"); record.setField("ip_target", FieldType.STRING, "255.255.255.255"); record.setField("url_scheme", FieldType.STRING, "http"); record.setField("url_host", FieldType.STRING, "origin-www.20minutes.fr"); record.setField("url_port", FieldType.STRING, "80"); record.setField("url_path", FieldType.STRING, "/r15lgc-100KB.js"); record.setField("request_size", FieldType.INT, 1399); record.setField("response_size", FieldType.INT, 452); record.setField("is_outside_office_hours", FieldType.BOOLEAN, false); record.setField("is_host_blacklisted", FieldType.BOOLEAN, false); // record.setField("tags", FieldType.ARRAY, new ArrayList<>(Arrays.asList("spam", "filter", // "mail"))); ByteArrayOutputStream baos = new ByteArrayOutputStream(); serializer.serialize(baos, record); baos.close(); String strEvent = new String(baos.toByteArray()); ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); Record deserializedRecord = serializer.deserialize(bais); assertTrue(deserializedRecord.equals(record)); }
void updateServer (ItemStack stack) { ByteArrayOutputStream bos = new ByteArrayOutputStream(8); DataOutputStream outputStream = new DataOutputStream(bos); try { outputStream.writeByte(2); outputStream.writeInt(logic.worldObj.provider.dimensionId); outputStream.writeInt(logic.xCoord); outputStream.writeInt(logic.yCoord); outputStream.writeInt(logic.zCoord); outputStream.writeShort(stack.itemID); outputStream.writeShort(stack.getItemDamage()); } catch (Exception ex) { ex.printStackTrace(); } Packet250CustomPayload packet = new Packet250CustomPayload(); packet.channel = "TConstruct"; packet.data = bos.toByteArray(); packet.length = bos.size(); PacketDispatcher.sendPacketToServer(packet); }
/** * processRequest processes PhaseIV Web Service calls. It creates a soap message from input string * xmlRequest and invokes Phase IV Web Service processRequest method. * * @param PhaseIV xmlRequest * @return PhaseIV xmlResponse * @throws Exception */ public String processRequest(String xmlRequest, String clientURL) throws Exception { try { if (Utils.getInstance().isNullString(xmlRequest) || Utils.getInstance().isNullString(clientURL)) { logger.debug("Recieved xmlRequest or clientURL as null"); return null; } logger.debug("processRequest--> xmlRequest :" + xmlRequest); ByteArrayInputStream inStream = new ByteArrayInputStream(xmlRequest.getBytes()); StreamSource source = new StreamSource(inStream); MessageFactory msgFactory = MessageFactory.newInstance(); SOAPMessage sMsg = msgFactory.createMessage(); SOAPPart sPart = sMsg.getSOAPPart(); sPart.setContent(source); MimeHeaders mimeHeader = sMsg.getMimeHeaders(); mimeHeader.setHeader("SOAPAction", "http://ejbs.phaseiv.bsg.adp.com"); logger.debug("processRequest-->in PhaseIVClient before call"); SOAPMessage respMsg = executeCall(sMsg, clientURL); logger.debug("processRequest-->in PhaseIVClient after call"); // SOAPFault faultCode = // respMsg.getSOAPPart().getEnvelope().getBody().getFault(); ByteArrayOutputStream outStream = new ByteArrayOutputStream(); respMsg.writeTo(outStream); logger.debug("processRequest xmlResponse:" + outStream.toString()); return outStream.toString(); } catch (Exception exp) { logger.error("processRequest --> Error while processing request : " + exp.getMessage()); logger.error("processRequest --> error xmlRequest:" + xmlRequest); exp.printStackTrace(); throw exp; } }
protected static void sendOutput() { System.setOut(originalStdout); System.setErr(originalStderr); LOG.info("Sending stdout content through logger: \n\n{}\n\n", outContent.toString()); LOG.info("Sending stderr content through logger: \n\n{}\n\n", errContent.toString()); }
void encode(DEROutputStream out) throws IOException { if (!empty) { ByteArrayOutputStream bOut = new ByteArrayOutputStream(); DEROutputStream dOut = new DEROutputStream(bOut); dOut.writeObject(obj); dOut.close(); byte[] bytes = bOut.toByteArray(); if (explicit) { out.writeEncoded(CONSTRUCTED | TAGGED | tagNo, bytes); } else { // // need to mark constructed types... // if ((bytes[0] & CONSTRUCTED) != 0) { bytes[0] = (byte) (CONSTRUCTED | TAGGED | tagNo); } else { bytes[0] = (byte) (TAGGED | tagNo); } out.write(bytes); } } else { out.writeEncoded(CONSTRUCTED | TAGGED | tagNo, new byte[0]); } }
@Test public void testDoFilterGzipResponseCompression() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(HttpMethod.POST.name(), "http://localhost:8080/gzip"); request.addHeader(HttpHeaders.ACCEPT_ENCODING, "gzip"); MockHttpServletResponse response = new MockHttpServletResponse(); MockFilterChain filterChain = new MockFilterChain( servlet, new GzipServletFilter(), new OncePerRequestFilter() { @Override protected void doFilterInternal( HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { response.getOutputStream().write("Should be compressed".getBytes()); } }); filterChain.doFilter(request, response); ByteArrayOutputStream unzippedStream = new ByteArrayOutputStream(); StreamUtils.copy( new GZIPInputStream(new ByteArrayInputStream(response.getContentAsByteArray())), unzippedStream); String unzipped = new String(unzippedStream.toByteArray()); Assert.assertEquals(unzipped, "Should be compressed"); }
@Override public void run() { try { ServerSocket ss = new ServerSocket(port); while (!interrupted()) { try (Socket s = ss.accept(); ) { InputStream in = s.getInputStream(); OutputStream out = s.getOutputStream(); ChannelLevelInputStream cin = new ChannelLevelInputStream(in); ChannelLevelPacket clp = cin.readPacket(); PALInputStream pin = new PALInputStream(new ByteArrayInputStream(clp.getPacketData())); PALRequest req = pin.readRequest(); PALResponse resp = process(req); ByteArrayOutputStream bout = new ByteArrayOutputStream(); PALOutputStream pout = new PALOutputStream(bout); pout.writePALResponse(resp); ChannelLevelPacket packet = new ChannelLevelPacket( clp.getAddressS(), clp.getAddressD(), 0x48, bout.toByteArray()); ChannelLevelOutputStream cout = new ChannelLevelOutputStream(out); cout.writePacket(packet); cout.close(); cin.close(); pout.close(); pin.close(); } catch (IOException e) { e.printStackTrace(); } } ss.close(); } catch (IOException e1) { e1.printStackTrace(); return; } }
private byte[] convertImage(int resImage) { Bitmap bitmap = BitmapFactory.decodeResource(getActivity().getResources(), resImage); ByteArrayOutputStream stream = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, 80, stream); // bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream); return stream.toByteArray(); }
/** * maintains a list of last <i>committedLog</i> or so committed requests. This is used for fast * follower synchronization. * * @param request committed request */ public void addCommittedProposal(Request request) { WriteLock wl = logLock.writeLock(); try { wl.lock(); if (committedLog.size() > commitLogCount) { committedLog.removeFirst(); minCommittedLog = committedLog.getFirst().packet.getZxid(); } if (committedLog.isEmpty()) { minCommittedLog = request.zxid; maxCommittedLog = request.zxid; } ByteArrayOutputStream baos = new ByteArrayOutputStream(); BinaryOutputArchive boa = BinaryOutputArchive.getArchive(baos); try { request.getHdr().serialize(boa, "hdr"); if (request.getTxn() != null) { request.getTxn().serialize(boa, "txn"); } baos.close(); } catch (IOException e) { LOG.error("This really should be impossible", e); } QuorumPacket pp = new QuorumPacket(Leader.PROPOSAL, request.zxid, baos.toByteArray(), null); Proposal p = new Proposal(); p.packet = pp; p.request = request; committedLog.add(p); maxCommittedLog = p.packet.getZxid(); } finally { wl.unlock(); } }
public byte[] getEncoded() throws IOException { ByteArrayOutputStream bOut = new ByteArrayOutputStream(); this.encode(bOut); return bOut.toByteArray(); }
@Test public void testAutoSend() throws Exception { ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); TelnetOutputStream out = new TelnetOutputStream(byteOut); out.autoSend(); out.flush(); byte[] message = byteOut.toByteArray(); Assert.assertNotNull("Auto message not sent", message); Assert.assertFalse("Auto message not sent", message.length == 0); Assert.assertTrue( "Error sending auto message. Expected length: " + TelnetOutputStream.autoMessage.length + ", actual length: " + message.length, message.length == TelnetOutputStream.autoMessage.length); for (int i = 0; i < message.length; i++) { Assert.assertEquals( "Wrong char in auto message. Position: " + i + ", expected: " + TelnetOutputStream.autoMessage[i] + ", read: " + message[i], TelnetOutputStream.autoMessage[i], message[i]); } }
public byte[] handleResponse(HttpResponse hr) throws ClientProtocolException, IOException { if (hr.getStatusLine().getStatusCode() == 200) { if (hr.getEntity().getContentEncoding() == null) { return EntityUtils.toByteArray(hr.getEntity()); } if (hr.getEntity().getContentEncoding().getValue().contains("gzip")) { GZIPInputStream gis = null; try { gis = new GZIPInputStream(hr.getEntity().getContent()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] b = new byte[1024]; int n; while ((n = gis.read(b)) != -1) baos.write(b, 0, n); System.out.println("Gzipped"); return baos.toByteArray(); } catch (IOException e) { throw e; } finally { try { if (gis != null) gis.close(); } catch (IOException ex) { throw ex; } } } return EntityUtils.toByteArray(hr.getEntity()); } if (hr.getStatusLine().getStatusCode() == 302) { throw new IOException("302"); } return null; }
public static String getResTxtContent(ClassLoader cl, String p) throws IOException { String s = res2txt_cont.get(p); if (s != null) return s; InputStream is = null; try { is = cl.getResourceAsStream(p); // is = this.getClass().getResourceAsStream(p); if (is == null) return null; byte[] buf = new byte[1024]; ByteArrayOutputStream baos = new ByteArrayOutputStream(); int len; while ((len = is.read(buf)) >= 0) { baos.write(buf, 0, len); } byte[] cont = baos.toByteArray(); s = new String(cont, "UTF-8"); res2txt_cont.put(p, s); return s; } finally { if (is != null) is.close(); } }
/** * 获取网络上的文件 * * @param URLName 地址 * @throws Exception */ public static byte[] getURLFile(String urlFile) throws Exception { ByteArrayOutputStream os = new ByteArrayOutputStream(); int HttpResult = 0; // 服务器返回的状态 URL url = new URL(urlFile); // 创建URL URLConnection urlconn = url.openConnection(); // 试图连接并取得返回状态码urlconn.connect(); HttpURLConnection httpconn = (HttpURLConnection) urlconn; HttpResult = httpconn.getResponseCode(); if (HttpResult != HttpURLConnection.HTTP_OK) { // 不等于HTTP_OK说明连接不成功 System.out.print("连接失败!"); } else { BufferedInputStream bis = new BufferedInputStream(urlconn.getInputStream()); BufferedOutputStream bos = new BufferedOutputStream(os); byte[] buffer = new byte[1024]; // 创建存放输入流的缓冲 int num = -1; // 读入的字节数 while (true) { num = bis.read(buffer); // 读入到缓冲区 if (num == -1) { bos.flush(); break; // 已经读完 } bos.flush(); bos.write(buffer, 0, num); } bos.close(); bis.close(); } return os.toByteArray(); }
public InputStream getInputStream() throws CoreException { if (filePath != null) { File file = new File(filePath); if (file.isFile()) { IMaven maven = MavenPlugin.getDefault().getMaven(); Settings settings = maven.buildSettings(null, filePath); List<Server> servers = settings.getServers(); if (servers != null) { for (Server server : servers) { server.setUsername(obfuscate(server.getUsername())); server.setPassword(obfuscate(server.getPassword())); server.setPassphrase(obfuscate(server.getPassphrase())); } } List<Proxy> proxies = settings.getProxies(); if (proxies != null) { for (Proxy proxy : proxies) { proxy.setUsername(obfuscate(proxy.getUsername())); proxy.setPassword(obfuscate(proxy.getPassword())); } } ByteArrayOutputStream baos = new ByteArrayOutputStream(1024 * 4); maven.writeSettings(settings, baos); return new ByteArrayInputStream(baos.toByteArray()); } } return null; }
private Bitmap comp(Bitmap image) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); image.compress(Bitmap.CompressFormat.JPEG, 100, baos); if (baos.toByteArray().length / 1024 > 1024) { // 判断如果图片大于1M,进行压缩避免在生成图片(BitmapFactory.decodeStream)时溢出 baos.reset(); // 重置baos即清空baos image.compress(Bitmap.CompressFormat.JPEG, 50, baos); // 这里压缩50%,把压缩后的数据存放到baos中 } ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray()); BitmapFactory.Options newOpts = new BitmapFactory.Options(); // 开始读入图片,此时把options.inJustDecodeBounds 设回true了 newOpts.inJustDecodeBounds = true; Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, newOpts); newOpts.inJustDecodeBounds = false; int w = newOpts.outWidth; int h = newOpts.outHeight; // 现在主流手机比较多是800*500分辨率,所以高和宽我们设置为 float hh = 800f; // 这里设置高度为800f float ww = 500f; // 这里设置宽度为500f // 缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可 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了 isBm = new ByteArrayInputStream(baos.toByteArray()); bitmap = BitmapFactory.decodeStream(isBm, null, newOpts); return compressImage(bitmap); // 压缩好比例大小后再进行质量压缩 }
/** 克隆Serializable */ @SuppressWarnings("unchecked") public static <T> T cloneSerializable(T src) throws RuntimeException { ByteArrayOutputStream memoryBuffer = new ByteArrayOutputStream(); ObjectOutputStream out = null; ObjectInputStream in = null; T dest = null; try { out = new ObjectOutputStream(memoryBuffer); out.writeObject(src); out.flush(); in = new ObjectInputStream(new ByteArrayInputStream(memoryBuffer.toByteArray())); dest = (T) in.readObject(); } catch (Exception e) { throw new RuntimeException(e); } finally { if (out != null) { try { out.close(); out = null; } catch (Exception e) { } } if (in != null) { try { in.close(); in = null; } catch (Exception e) { } } } return dest; }
private byte[] serialise(Object value, VersionMapper versionMapper) throws IOException { ByteArrayOutputStream bout = new ByteArrayOutputStream(); ObjectOutputStream oout = new LenientObjectOutputStream(bout, versionMapper); oout.writeObject(value); oout.close(); return bout.toByteArray(); }
public byte[] getContentHash() { byte[] bytes = null; try { ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); ObjectOutputStream objectStream = new ObjectOutputStream(byteStream); objectStream.writeObject(components); objectStream.writeObject(pointers); objectStream.flush(); bytes = byteStream.toByteArray(); } catch (IOException ioe) { // too bad we don't have a good way to throw a serialziation exception return null; } MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { return null; } md.reset(); md.update(bytes); return md.digest(); }