【android】bitmap轉換與處理相關工具類,Bitmap與DrawAble與byte[]與InputStream之間的轉換

1.將view轉爲bitmap

 

public static Bitmap getBitmapFromView(View view)
{
    // Define a bitmap with the same size as the view
    Bitmap returnedBitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
    // Bind a canvas to it
    Canvas canvas = new Canvas(returnedBitmap);
    // Get the view's background
    Drawable bgDrawable = view.getBackground();
    if (bgDrawable != null)
        // has background drawable, then draw it on the canvas
        bgDrawable.draw(canvas);
    else
        // does not have background drawable, then draw white background on
        // the canvas
        canvas.drawColor(Color.WHITE);
    // draw the view on the canvas
    view.draw(canvas);
    // return the bitmap
    return returnedBitmap;
}



2.將view轉爲bitmap

public static Bitmap viewToBitmap(View view)
{
    view.setDrawingCacheEnabled(true);
    view.buildDrawingCache();
    Bitmap bm = view.getDrawingCache();
    return bm;
}




3.將xml轉爲bitmap

public static Bitmap convertBitmapFromXML(Context context, String clusterSize, Bitmap bm)
{
                                                                                                                                                                                                                                                                                                                                                                                        
    View layout = LayoutInflater.from(context).inflate(R.layout.estatecartlist_item, null);
    View bitmapView = layout.findViewById(R.id.estatecartlist_item_bitmap);
    TextView xml_text = (TextView) layout.findViewById(R.id.item_estatecart_tv_name);
    ImageView image = (ImageView) layout.findViewById(R.id.item_estatecart_iv_main);
    image.setImageBitmap(bm);
    xml_text.setText(clusterSize);
                                                                                                                                                                                                                                                                                                                                                                                        
    bitmapView.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
                                                                                                                                                                                                                                                                                                                                                                                        
    bitmapView.layout(0, 0, bitmapView.getMeasuredWidth(), bitmapView.getMeasuredHeight());
                                                                                                                                                                                                                                                                                                                                                                                        
    final Bitmap clusterBitmap = Bitmap.createBitmap(bitmapView.getMeasuredWidth(), bitmapView.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
                                                                                                                                                                                                                                                                                                                                                                                        
    Canvas canvas = new Canvas(clusterBitmap);
    bitmapView.draw(canvas);
    return clusterBitmap;
}




==============參考資料===================
* 1.http://stackoverflow.com/questions/7200535/how-to-convert-views-to-bitmap
* 2.http://stackoverflow.com/questions/5536066/convert-view-to-bitmap-on-android/9595919#9595919
* 3.http://stackoverflow.com/questions/12402392/android-converting-xml-view-to-bitmap-without-showing-it





4.圖片縮放與壓縮

private Bitmap getimage(String srcPath)
{
    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;
    // 現在主流手機比較多是800*480分辨率,所以高和寬我們設置爲
    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);
    return compressImage(bitmap);// 壓縮好比例大小後再進行質量壓縮
}
// 圖片質量壓縮
private static Bitmap compressImage(Bitmap image)
{
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 質量壓縮方法,這裏100表示不壓縮,把壓縮後的數據存放到baos中
    int options = 100;
    while (baos.toByteArray().length / 1024 > 100)
    { // 循環判斷如果壓縮後圖片是否大於100kb,大於繼續壓縮
        baos.reset();// 重置baos即清空baos
        image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 這裏壓縮options%,把壓縮後的數據存放到baos中
        options -= 10;// 每次都減少10
    }
    ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把壓縮後的數據baos存放到ByteArrayInputStream中
    Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream數據生成圖片
    return bitmap;
}
// 圖片按比例大小壓縮
private static 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*480分辨率,所以高和寬我們設置爲
    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了
    isBm = new ByteArrayInputStream(baos.toByteArray());
    bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
    return compressImage(bitmap);// 壓縮好比例大小後再進行質量壓縮
}




5.圖片轉爲文件

public static boolean saveBitmap2file(Bitmap bmp, String filename)
{
    CompressFormat format = Bitmap.CompressFormat.JPEG;
    int quality = 100;
    OutputStream stream = null;
    try
    {
        stream = new FileOutputStream("/sdcard/" + filename);
    }
    catch (FileNotFoundException e)
    {
        e.printStackTrace();
    }
                                                                                                                                                                                                                                                                                                                                                                      
    return bmp.compress(format, quality, stream);
}



6.屏幕截屏方法

// 獲取當前屏幕bitmap,轉換成bytes[] 調用 UI分享方法
public void printscreen_share(View v)
{
    View view1 = getWindow().getDecorView();
    Display display = getWindowManager().getDefaultDisplay();
    view1.layout(0, 0, display.getWidth(), display.getHeight());
    view1.setDrawingCacheEnabled(true);
    Bitmap bitmap = Bitmap.createBitmap(view1.getDrawingCache());
}




7.把Bitmap 轉成 Byte

public static byte[] Bitmap2Bytes(Bitmap bm)
{
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
    return baos.toByteArray();
}



8.圖片轉爲文件

public static boolean saveBitmap2file(Bitmap bmp)
{
    CompressFormat format = Bitmap.CompressFormat.PNG;
    int quality = 100;
    OutputStream stream = null;
    try
    {
        // 判斷SDcard狀態
        if (!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()))
        {
            // 錯誤提示
            return false;
        }
                                                                                                                                                                                                                                                                                                        
        // 檢查SDcard空間
        File SDCardRoot = Environment.getExternalStorageDirectory();
        if (SDCardRoot.getFreeSpace() < 10000)
        {
            // 彈出對話框提示用戶空間不夠
            Log.e("Utils", "存儲空間不夠");
            return false;
        }
                                                                                                                                                                                                                                                                                                        
        // 在SDcard創建文件夾及文件
        File bitmapFile = new File(SDCardRoot.getPath() + FILE_PATH);
        bitmapFile.getParentFile().mkdirs();// 創建文件夾
        stream = new FileOutputStream(SDCardRoot.getPath() + FILE_PATH);// "/sdcard/"
    }
    catch (FileNotFoundException e)
    {
        e.printStackTrace();
    }
    return bmp.compress(format, quality, stream);
}




9.下載圖片

public static Bitmap loadImage(String... params)
{
    InputStream is = null;
    Bitmap bitmap = null;
    try
    {
        URL url = new URL(params[0]);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(5000);
        conn.setConnectTimeout(5000);
        if (HttpURLConnection.HTTP_OK != conn.getResponseCode())
        {
            // 網絡連接異常
            Log.e("", "loadImage連接異常");
            return null;
        }
                                                                                                                                                                                                                                                                           
        is = conn.getInputStream();
        bitmap = BitmapFactory.decodeStream(is);
                                                                                                                                                                                                                                                                           
    }
    catch (MalformedURLException e)
    {
        e.printStackTrace();
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
    finally
    {
        if (null != is)
        {
            try
            {
                is.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }
    return bitmap;
}



10.byte[]轉換成Bitmap

public static Bitmap Bytes2Bitmap(byte[] b)
{
    if (b.length != 0)
    {
        return BitmapFactory.decodeByteArray(b, 0, b.length);
    }
    return null;
}



11.將字符串轉換成Bitmap類型

public static Bitmap stringtoBitmap(String string)
{
    // 將字符串轉換成Bitmap類型
    Bitmap bitmap = null;
    try
    {
        byte[] bitmapArray;
        bitmapArray = Base64.decode(string, Base64.DEFAULT);
        bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0, bitmapArray.length);
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
                                                                                                                                                                                                                                             
    return bitmap;
}




12.將Bitmap轉換成字符串

public static String bitmaptoString(Bitmap bitmap)
{
    // 將Bitmap轉換成字符串
    String string = null;
    ByteArrayOutputStream bStream = new ByteArrayOutputStream();
    bitmap.compress(CompressFormat.PNG, 100, bStream);
    byte[] bytes = bStream.toByteArray();
    string = Base64.encodeToString(bytes, Base64.DEFAULT);
    return string;
}



13.byte[]轉爲文件

public static File getFileFromBytes(byte[] b)
{
    BufferedOutputStream stream = null;
    File file = null;
    try
    {
        // 判斷SDcard狀態
        if (!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()))
        {
            // 錯誤提示
            return null;
        }
                                                                                                                                                                                                                       
        // 檢查SDcard空間
        File SDCardRoot = Environment.getExternalStorageDirectory();
        if (SDCardRoot.getFreeSpace() < 10000)
        {
            // 彈出對話框提示用戶空間不夠
            Log.e("Utils", "存儲空間不夠");
            return null;
        }
                                                                                                                                                                                                                       
        // 在SDcard創建文件夾及文件
        File bitmapFile = new File(SDCardRoot.getPath() + FILE_PATH);
        bitmapFile.getParentFile().mkdirs();// 創建文件夾
                                                                                                                                                                                                                       
        FileOutputStream fstream = new FileOutputStream(bitmapFile);
        stream = new BufferedOutputStream(fstream);
        stream.write(b);
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
    finally
    {
        if (stream != null)
        {
            try
            {
                stream.close();
            }
            catch (IOException e1)
            {
                e1.printStackTrace();
            }
        }
    }
    return file;
}




14.圖片壓縮

public static Bitmap scaleDownBitmap(Bitmap photo, int newHeight, Context context)
{
                                                                                                                                                                                                        
    final float densityMultiplier = context.getResources().getDisplayMetrics().density;
                                                                                                                                                                                                        
    int h = (int) (newHeight * densityMultiplier);
    int w = (int) (h * photo.getWidth() / ((double) photo.getHeight()));
                                                                                                                                                                                                        
    photo = Bitmap.createScaledBitmap(photo, w, h, true);
                                                                                                                                                                                                        
    return photo;
}


15.將byte[]轉換成InputStream

public InputStream Byte2InputStream(byte[] b)
{
    ByteArrayInputStream bais = new ByteArrayInputStream(b);
    return bais;
}




16.將InputStream轉換成byte[]

public byte[] InputStream2Bytes(InputStream is)
{
    String str = "";
    byte[] readByte = new byte[1024];
    int readCount = -1;
    try
    {
        while ((readCount = is.read(readByte, 0, 1024)) != -1)
        {
            str += new String(readByte).trim();
        }
        return str.getBytes();
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
    return null;
}



17.將Bitmap轉換成InputStream

public InputStream Bitmap2InputStream(Bitmap bm)
{
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);
    InputStream is = new ByteArrayInputStream(baos.toByteArray());
    return is;
}




18.將Bitmap轉換成InputStream

public InputStream Bitmap2InputStream(Bitmap bm, int quality)
{
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bm.compress(Bitmap.CompressFormat.PNG, quality, baos);
    InputStream is = new ByteArrayInputStream(baos.toByteArray());
    return is;
}




19.將InputStream轉換成Bitmap

public Bitmap InputStream2Bitmap(InputStream is)
{
    return BitmapFactory.decodeStream(is);
}



20.Drawable轉換成InputStream

public InputStream Drawable2InputStream(Drawable d)
{
    Bitmap bitmap = this.drawable2Bitmap(d);
    return this.Bitmap2InputStream(bitmap);
}




21.InputStream轉換成Drawable

public Drawable InputStream2Drawable(InputStream is)
{
    Bitmap bitmap = this.InputStream2Bitmap(is);
    return this.bitmap2Drawable(bitmap);
}


22.Drawable轉換成byte[]

public byte[] Drawable2Bytes(Drawable d)
{
    Bitmap bitmap = this.drawable2Bitmap(d);
    return this.Bitmap2Bytes(bitmap);
}



23.byte[]轉換成Drawable

public Drawable Bytes2Drawable(byte[] b)
{
    Bitmap bitmap = this.Bytes2Bitmap(b);
    return this.bitmap2Drawable(bitmap);
}



24.Drawable轉換成Bitmap

public Bitmap drawable2Bitmap(Drawable drawable)
{
    Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(),
            drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565);
    Canvas canvas = new Canvas(bitmap);
    drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
    drawable.draw(canvas);
    return bitmap;
}



25.Bitmap轉換成Drawable

public Drawable bitmap2Drawable(Bitmap bitmap)
{
    BitmapDrawable bd = new BitmapDrawable(bitmap);
    Drawable d = (Drawable) bd;
    return d;
}

 

轉自http://blog.14401.cn/post-156.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章