public static Bitmap getUrlBitmap(String path) { Bitmap bm = null; try { URL url = new URL(path);//创建一个URL对象,其参数为网络图片的链接地址 //使用一个URL对象开启一个链接 HttpURLConnection con = (HttpURLConnection) url.openConnection(); //设置相关参数 con.setDoInput(true); con.setUseCaches(true); //不允许使用缓存 con.setConnectTimeout(5000);//设置超时 con.setReadTimeout(10000); con.connect(); int code = con.getResponseCode(); if (code==200) { InputStream is = con.getInputStream();//获取输入流 bm = getFitSampleBitmap(is);//将输入流解码为Bitmap对象 is.close(); } con.disconnect(); } catch (Exception e) { e.printStackTrace(); } return bm; } /*** * 读取获得Bitmap对象 * @param inputStream * @return * @throws Exception */ public static Bitmap getFitSampleBitmap(InputStream inputStream) throws Exception{ BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true;//设置该项可以获得图片原始宽高度 byte[] bytes = readStream(inputStream); BitmapFactory.decodeByteArray(bytes, 0, bytes.length, options); options.inSampleSize=computeSampleSize(options, -1, 128*128); options.inJustDecodeBounds=false; return BitmapFactory.decodeByteArray(bytes, 0, bytes.length, options); } /** * 从inputStream中获取字节流 数组大小 **/ public static byte[] readStream(InputStream inStream) throws Exception{ ByteArrayOutputStream outStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = 0; while ((len = inStream.read(buffer)) != -1) { outStream.write(buffer, 0, len); } outStream.close(); inStream.close(); return outStream.toByteArray(); } /*** * 计算图片大小 * @param options * @param minSideLength * @param maxNumOfPixels * @return */ public static int computeSampleSize(BitmapFactory.Options options, int minSideLength, int maxNumOfPixels) { int initialSize = computeInitialSampleSize(options, minSideLength, maxNumOfPixels); int roundedSize; if (initialSize <= 8) { roundedSize = 1; while (roundedSize < initialSize) { roundedSize <<= 1; } } else { roundedSize = (initialSize + 7) / 8 * 8; } return roundedSize; } /*** * 计算获得图片大小 * @param options * @param minSideLength * @param maxNumOfPixels * @return */ private static int computeInitialSampleSize(BitmapFactory.Options options,int minSideLength, int maxNumOfPixels) { double w = options.outWidth; double h = options.outHeight; int lowerBound = (maxNumOfPixels == -1) ? 1 : (int) Math.ceil(Math.sqrt(w * h / maxNumOfPixels)); int upperBound = (minSideLength == -1) ? 128 :(int) Math.min(Math.floor(w / minSideLength), Math.floor(h / minSideLength)); if (upperBound < lowerBound) { // return the larger one when there is no overlapping zone. return lowerBound; } if ((maxNumOfPixels == -1) && (minSideLength == -1)) { return 1; } else if (minSideLength == -1) { return lowerBound; } else { return upperBound; } }
android请求获取图片的方法
最新推荐文章于 2023-06-25 20:47:10 发布