android 一些相关处理网络图片与音乐(部分转载)

    技术2022-05-20  60

    1.已知图片网址,获得图像资源:

    public Bitmap getBmp(URL imgUrl){ URL url=new URL(imgUrl); URLConnection conn=url.openConnection(); conn.connect(); Bitmap bm=BitmapFactory.decodeStream(conn.getInputStream()); return bm; }

    android 图片编辑时需要从外界(sdcard ,res/.png...,xml)读取图片到画布,其中从sdcard读取图片到画布的过程如下: public void drawBitMapFromSDcard(String dir) { if(dir ==null || dir.equals("")){ return ; } bitMap = BitmapFactory.decodeFile(dir); int width = bitMap.getWidth(); int height = bitMap.getHeight(); 如果图片像素太大超过手机屏幕大小可以按照手机屏比例进行缩放 if (width > 320 && height > 480) { int newWidth = 320; int newHeight = 480; float scaleWidth = ((float) newWidth) / width; float scaleHeight = ((float) newHeight) / height; float minScale = Math.min(scaleWidth, scaleHeight); matrix = new Matrix(); matrix.postScale(minScale, minScale); bitMap = Bitmap.createBitmap(bitMap, 0, 0, width, height, matrix, true); } 显示图片到手机屏幕 mCanvas.drawBitmap(bitMap, 0, 0, mPaint); invalidate(); (二)图片剪切 在android 画布上对图像进行剪切时,首先选中一块区域,得到所选区域的像素点,然后放到到要粘贴的位置。剪切代码如下 public int[] getClipRectangePix(RectF rectf, Bitmap bitmap) { int width = (int) rectf.width(); int height = (int) rectf.height(); int[] clipRectangePix = new int[(width * height)];// ???? int x = (int) rectf.left; int y = (int) rectf.top; bitmap.getPixels(clipRectangePix, 0, width, x, y, width, height); // Log.v("pix Color:",""+ clipRectangePix[0] ); return clipRectangePix; }

    ResponseCodeResponseMessage说明200OK成功401Unauthorized未授权500Internal Server Error服务器内部错误404Not Found找不到网页

    2.播放网络音乐

    a.通过MediaPlayer的setDataSource()对MP3文件进行“缓冲流”的播放,此方法没有对音乐文件进行保存,适用于在线试听,具体使用方法是:

    MediaPlayer mp=new MediaPlayer(); try{ mp.setDataSource(XXX.this,Uri.parse("musicURL")); mp.prepare(); mp.start(); }catch(Exception e){ } 

    b.将在线音乐下载下来才能试听,具体方法:

    MediaPlayer mp=new MediaPlayer(); final Runnable r = new Runnable() { public void run() { try { setDataSource("http://XXX/XXX/XXX.mp3"); mp.prepare(); mp.start(); } catch (Exception e) { } } }; new Thread(r).start(); /** *musicurl为音乐网址或者是本地绝对地址 **/ public void setDataSource(String musicurl) throws Exception { if (!URLUtil.isNetworkUrl(musicurl)) { mp.setDataSource(musicurl); } else { try { URL url = new URL(musicurl); URLConnection conn = url.openConnection(); conn.connect(); InputStream is = conn.getInputStream(); if(is==null){ throw new RuntimeException("stream is null"); } String extentions=musicurl.substring(musicurl.lastIndexOf(".")+1);//取扩展名 if(extentions==""){ extentions="dat"; } File mp3file = File.createTempFile("yk3372", "."+extentions); String path = mp3file.getAbsolutePath();//存放本地的具体地址 FileOutputStream fos = new FileOutputStream(path); byte buf[] = new byte[128]; do { int numread = is.read(buf); if (numread <= 0) { break; } fos.write(buf, 0, numread); } while (true); mp.setDataSource(path); try { is.close(); } catch (Exception e) { } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }


    最新回复(0)