安卓开发截取当前屏幕图片及截取整个ListView图片并保存到本地

Posted Gradle官方文件

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了安卓开发截取当前屏幕图片及截取整个ListView图片并保存到本地相关的知识,希望对你有一定的参考价值。

安卓开发截取当前屏幕图片及截取整个ListView图片并保存到本地


import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.Log;
import android.view.View;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ScrollView;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/2/21.
 */

public class ScreenUtil 
    // 获取指定Activity的截屏
    public static Bitmap takeScreenShot(Activity activity) 
        // View是你需要截图的View
        View view = activity.getWindow().getDecorView();
        view.setDrawingCacheEnabled(true);
        view.buildDrawingCache();
        Bitmap b1 = view.getDrawingCache();

        // 获取状态栏高度
        Rect frame = new Rect();
        activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
        int statusBarHeight = frame.top;
        System.out.println(statusBarHeight);

        // 获取屏幕长和高
        int width = activity.getWindowManager().getDefaultDisplay().getWidth();
        int height = activity.getWindowManager().getDefaultDisplay()
                .getHeight();
        // 去掉标题栏
        // Bitmap b = Bitmap.createBitmap(b1, 0, 25, 320, 455);
        Bitmap b = Bitmap.createBitmap(b1, 0, statusBarHeight, width, height
                - statusBarHeight);
        view.destroyDrawingCache();
        return b;
    


  /**
     * 截取Listview的屏幕
     * **/
    public static Bitmap getWholeListViewItemsToBitmap(ListView listview) 

        ListAdapter adapter  = listview.getAdapter();
        int itemscount       = adapter.getCount();
        int allitemsheight   = 0;
        List<Bitmap> bmps    = new ArrayList<Bitmap>();

        for (int i = 0; i < itemscount; i++) 

            View childView      = adapter.getView(i, null, listview);
            childView.measure(View.MeasureSpec.makeMeasureSpec(listview.getWidth(), View.MeasureSpec.EXACTLY),
                    View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));

            childView.layout(0, 0, childView.getMeasuredWidth(), childView.getMeasuredHeight());
            childView.setDrawingCacheEnabled(true);
            childView.buildDrawingCache();
            bmps.add(childView.getDrawingCache());
            allitemsheight+=childView.getMeasuredHeight();
        

        Bitmap bigbitmap    = Bitmap.createBitmap(listview.getMeasuredWidth(), allitemsheight, Bitmap.Config.ARGB_8888);
        Canvas bigcanvas    = new Canvas(bigbitmap);

        Paint paint = new Paint();
        int iHeight = 0;

        for (int i = 0; i < bmps.size(); i++) 
            Bitmap bmp = bmps.get(i);
            bigcanvas.drawBitmap(bmp, 0, iHeight, paint);
            iHeight+=bmp.getHeight();

            bmp.recycle();
            bmp=null;
        


        return bigbitmap;
    

//将BitMap图片保存到本地
    public static boolean saveMyBitmap(Bitmap bmp, String bitName) throws IOException 
        File dirFile = new File("./sdcard/Screen/");
        if (!dirFile.exists()) 
            dirFile.mkdirs();
        
        File f = new File("./sdcard/Screen/" + bitName + ".png");
        boolean flag = false;
        f.createNewFile();
        FileOutputStream fOut = null;
        try 
            fOut = new FileOutputStream(f);
            bmp.compress(Bitmap.CompressFormat.PNG, 100, fOut);
            flag = true;
         catch (FileNotFoundException e) 
            e.printStackTrace();
        
        try 
            fOut.flush();
         catch (IOException e) 
            e.printStackTrace();
        
        try 
            fOut.close();
         catch (IOException e) 
            e.printStackTrace();
        
        return flag;
    





使用方式:

            case R.id.btnScreenShoot:
                Bitmap bitmap1 = ScreenUtil.takeScreenShot(MainActivity.this);
                iv.setImageBitmap(bitmap1);
                try 
                    ScreenUtil.saveMyBitmap(bitmap1,"短:"+System.currentTimeMillis());
                 catch (IOException e) 
                    e.printStackTrace();
                
                break;
            case R.id.btnScreenShootListView:
                new Thread()
                    @Override
                    public void run() 
                        super.run();
                        final Bitmap bitmap2 = ScreenUtil.getWholeListViewItemsToBitmap(mLV);
                        try 
                            ScreenUtil.saveMyBitmap(bitmap2,"长:"+System.currentTimeMillis());
                         catch (IOException e) 
                            e.printStackTrace();
                        
                        iv.post(new Runnable() 
                            @Override
                            public void run() 
                                iv.setImageBitmap(bitmap2);
                            
                        );
                    
                .start();
                break;

截取ScrowView图片

     /**
      * 截取scrollview的屏幕
      * @param scrollView
      * @return
      */
      public static Bitmap getBitmapByView(ScrollView scrollView) 
         int h = 0;
         Bitmap bitmap = null;
         // 获取scrollview实际高度
         for (int i = 0; i < scrollView.getChildCount(); i++) 
             h += scrollView.getChildAt(i).getHeight();
             scrollView.getChildAt(i).setBackgroundColor(
                     Color.parseColor("#ffffff"));
             
         // 创建对应大小的bitmap
         bitmap = Bitmap.createBitmap(scrollView.getWidth(), h,
                  Bitmap.Config.RGB_565);
         final Canvas canvas = new Canvas(bitmap);
         scrollView.draw(canvas);
         return bitmap;
      

图片压缩有关方法

    /**
     * 质量压缩
     *
     */
    public static Bitmap compressBmp(Bitmap bmp,int setSize)
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int options = 100;//个人喜欢从80开始,
        bmp.compress(Bitmap.CompressFormat.JPEG, options, baos);
        while (baos.toByteArray().length / 1024 > setSize) 
            baos.reset();
            options -= 10;
            bmp.compress(Bitmap.CompressFormat.JPEG, options, baos);
            Log.i("123", "压缩大小-:----------->>>>>>>>>>>>>>>>>>>>>>>>>>"+baos.toByteArray().length / 1024 );
            Log.i("123", "要求大小-:----------->>>>>>>>>>>>>>>>>>>>>>>>>>"+setSize );
            Log.i("123", "options-:----------->>>>>>>>>>>>>>>>>>>>>>>>>>"+options );
        
        return bmp;
    


    public static Bitmap compressBitmap(Bitmap bitmap,int size)
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 85, out);
        float zoom = (float)Math.sqrt(size * 1024 / (float)out.toByteArray().length);

        Matrix matrix = new Matrix();
        matrix.setScale(zoom, zoom);

        Bitmap result = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);

        out.reset();
        result.compress(Bitmap.CompressFormat.JPEG, 85, out);
        while(out.toByteArray().length > size * 1024)
            Log.i("123", "aout.toByteArray().length ----------->>>>>>>>>>>>: "+out.toByteArray().length );
            Log.i("123", "asize * 1024 ------------------------>>>>>>>>>>>>: "+size * 1024 );
            out.reset();
            result.compress(Bitmap.CompressFormat.JPEG, 85, out);
            System.out.println(out.toByteArray().length);
            matrix.setScale(0.9f, 0.9f);
            result = Bitmap.createBitmap(result, 0, 0, result.getWidth(), result.getHeight(), matrix, true);

        
        return result;
    

不要忘记添加权限

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

以上是关于安卓开发截取当前屏幕图片及截取整个ListView图片并保存到本地的主要内容,如果未能解决你的问题,请参考以下文章

如何在颤动中截取屏幕之外的小部件屏幕截图?

截屏快捷键

android 怎么获取当前屏幕的截图

AWT Robot - 仅在 MacOS 上截取当前程序的屏幕截图

以编程方式截取 iOS 中另一个应用程序的整个可滚动区域的屏幕截图

截取屏幕的一块区域并且声称图片