Upload compressed images and maintain 100k distortion-less method

Source: Internet
Author: User
Tags response code

The method of compressing the 100k picture is not distorted, first obtains the original length and width of the picture, then calculates the scale value of the picture, and finally the proportional compression;


The following code is a compressed tool class;

public class Pictureutil {/** * Main method * * @param filePath * @return */public static InputStream bitmaptostring (String filep ATH) {Bitmap BM = Getsmallbitmap (FilePath); Bytearrayoutputstream BAOs = new Bytearrayoutputstream () bm.compress (Bitmap.CompressFormat.JPEG, BAOs);// The compressed data BAOs stored in the bytearrayinputstream bytearrayinputstream ISBM = new Bytearrayinputstream (Baos.tobytearray ()); return ISBM;} /** * Calculate the zoom value of the picture * * @param options * @param reqwidth * @param reqheight * @return */public static int Calculateinsamplesiz E (bitmapfactory.options options,int reqwidth, int reqheight) {//Raw height and width of imagefinal int height = OPTIONS.O utheight;final int width = Options.outwidth;int insamplesize = 1;if (height > Reqheight | | width > reqwidth) {//Cal Culate ratios of height and width to requested height and//widthfinal int heightratio = Math.Round ((float) height/(float Reqheight), final int widthRatio = Math.Round ((float) width/(float) reqwidth);//Choose the smallest ratio as InSAmplesize value, this will//guarantee//a final image with both dimensions larger than or equal to the//requested height and width.insamplesize = HeightRatio < WidthRatio? Heightratio:widthratio;} return insamplesize;}  /** * Breakthrough based on path and compression return BITMAP used to display * * @param imagesrc * @return */public static Bitmap getsmallbitmap (String filePath) {final Bitmapfactory.options Options = new Bitmapfactory.options (); options.injustdecodebounds = true; Bitmapfactory.decodefile (FilePath, options);//Calculate insamplesizeoptions.insamplesize = Calculateinsamplesize ( options, 480);//Decode bitmap with insamplesize setoptions.injustdecodebounds = False;return Bitmapfactory.decodefile (FilePath, options);} /** * Delete Picture According to path * * @param path */public static void Deletetempfile (String path) {File File = new file (path); if (File.exis TS ()) {File.delete ();}} /** * Added to gallery */public static void Galleryaddpic (context context, String path) {Intent mediascanintent = new Intent (intent.a Ction_media_scanner_scan_file); FiLe f = new File (path); Uri Contenturi = Uri.fromfile (f); Mediascanintent.setdata (Contenturi); Context.sendbroadcast (mediaScanIntent);} /** * Gets the directory where the picture is saved * * @return */public static file Getalbumdir () {File dir = new file (Environment.getexternalstoragepublicd Irectory (Environment.directory_pictures), Getalbumname ()), if (!dir.exists ()) {dir.mkdirs ();} return dir;} /** * Get the Picture folder name to save hidden trouble Check * * @return */public static String Getalbumname () {return ' Sheguantong ';}}

The following is the upload image of the tool class, only need to provide a picture URL, you can;

* * Upload Tool class upload compression; * @author Spring Sky * email:[email protected] * qq:840950105 * MyName: Shi Ming */public class Uploadut   Il {private static final String TAG = "UploadFile";p rivate static final int time_out = 10*1000; Timeout time private static final String CHARSET = "Utf-8"; Set Encoding/** * Android upload file to server * @param file need to upload files * @param requesturl request Rul * @return Return the contents of the response */public static String u Ploadfile (String file,string requesturl) {string result = NULL;  String boundary = Uuid.randomuuid (). toString (); The boundary identifier randomly generates a string PREFIX = "--", Line_end = "\ r \ n";   String content_type = "Multipart/form-data"; Content type try {URL url = new URL (requesturl); HttpURLConnection conn = (httpurlconnection) url.openconnection (); Conn.setreadtimeout (time_out);  Conn.setconnecttimeout (time_out); Conn.setdoinput (true); Allow input stream Conn.setdooutput (true);  Allow output stream conn.setusecaches (false);  Cache Conn.setrequestmethod ("POST") is not allowed;  Request Mode Conn.setrequestproperty ("Charset", Charset); Set the encoding Conn.setrequestproperty ("ConnectIon "," keep-alive "); Conn.setrequestproperty ("Content-type", Content_Type + "; boundary=" + boundary); if (file!=null) {/** * When the file is not empty, wrap the file and upload the */dataoutputstream dos = new DataOutputStream (Conn.getoutputstream ()); Nputstream is =pictureutil.bitmaptostring (file); byte[] bytes = new Byte[9000];int len = 0;while ((len=is.read (bytes))!=- 1) {dos.write (bytes, 0, len);} Is.close ();d os.write (Line_end.getbytes ()); byte[] End_data = (prefix+boundary+prefix+line_end). GetBytes ();  Dos.write (End_data);d Os.flush ();/** * Get response Code 200 = Success * When the response is successful, get the stream of the response */int res = Conn.getresponsecode (); LOG.E (Tag, "Response code:" +res);//if (res==200)//{LOG.E (tag, "request Success"); Inputstrea M input = Conn.getinputstream (); StringBuffer sb1= new StringBuffer (); int SS; while ((Ss=input.read ())!=-1) {sb1.append ((char) SS);} result = Sb1.tostring (); LOG.E (Tag, "Result:" + result);//}//else{//LOG.E (tag, "Request Error" ),//}}} catch (Malformedurlexception e) {e.printstacktrace ();} catch (IOException e) {e.printstacktrace ();} return result;} public static InputStream compressimage (String file) {Bitmap Bitmap = bitmapfactory.decodefile (file); Bitmapfactory.options newopts = new Bitmapfactory.options ();//start reading into the picture, At this point the options.injustdecodebounds is set to Truenewopts.injustdecodebounds = True;bitmap = Bitmapfactory.decodefile (file, newopts); newopts.injustdecodebounds = False;int W = newopts.outwidth;int h = newopts.outheight;//Set resolution float HH = 800f;flo at ww = 400f;//Zoom ratio. Because it is a fixed scale, it can only be calculated with one of the high or wide data, int be = 1;if (W > H && w > ww) {//If the width is large, scale be = (int) According to the fixed width size (newopts.outwid TH/WW);} else if (W < h && h > hh) {//If the width is large then the BE = (int) (NEWOPTS.OUTHEIGHT/HH) is scaled according to the fixed width size;} if (be <= 0) {is = 1;} Newopts.insamplesize = be;//Set scaling//Reread the picture, note that at this point the Newopts.injustdecodebounds = Falsebitmap = Bitmapfactory.decodefile (file, newopts); try {//bitmap bitmapyas=compressimage1 (Bitmap); return CompressImage2 ( bitmap);} CAtch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace (); return null;}} public static InputStream CompressImage2 (Bitmap Bitmap) throws Exception {try {bytearrayoutputstream BAOs = new Bytearrayo Utputstream (); Bitmap.compress (Bitmap.CompressFormat.JPEG, BAOs); int options = 100;int size = Baos.tobytearray (). Length/1024;while (Size > Max && options > 0) {baos.reset ();//reset BAOs that is empty baosoptions-=10;//each time reduce 10//here compression o ptions%, the compressed data is stored in the BAOs bitmap.compress (Bitmap.CompressFormat.JPEG, Options, baos); size = Baos.tobytearray (). length /1024;} The compressed data BAOs stored in the bytearrayinputstream bytearrayinputstream ISBM = new Bytearrayinputstream (Baos.tobytearray ()); return ISBM;} catch (Exception e) {throw e;}}}


Upload compressed images and maintain 100k distortion-less method

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.