Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/233.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 如何在位图中获取签名图像_Android - Fatal编程技术网

Android 如何在位图中获取签名图像

Android 如何在位图中获取签名图像,android,Android,这是signatureView类 public class MainActivity extends Activity { LinearLayout mContent; signature mSignature; Button mClear, mGetSign, mCancel; public static String tempDir; public int count = 1; public String current = null;

这是signatureView类

public class MainActivity extends Activity {

    LinearLayout mContent;
    signature mSignature;
    Button mClear, mGetSign, mCancel;
    public static String tempDir;
    public int count = 1;
    public String current = null;
    private Bitmap mBitmap;
    View mView;
    File mypath;

    private String uniqueId;
    private EditText yourName;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.signature);
        uniqueId = "Sign" + Math.random();
        current = uniqueId + ".png";
        mContent = (LinearLayout) findViewById(R.id.linearLayout);
        mSignature = new signature(this, null);
        mSignature.setBackgroundColor(Color.WHITE);
        mContent.addView(mSignature, LayoutParams.FILL_PARENT,
                LayoutParams.FILL_PARENT);
        mClear = (Button) findViewById(R.id.clear);
        mGetSign = (Button) findViewById(R.id.getsign);
        mGetSign.setEnabled(false);
        mCancel = (Button) findViewById(R.id.cancel);
        mView = mContent;

        mGetSign.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                Log.v("log_tag", "Panel Saved");
                boolean error = captureSignature();
                if (!error) {
                    mView.setDrawingCacheEnabled(true);
                    mSignature.save(mView);
                    Bundle b = new Bundle();
                    b.putString("status", "done");
                    Intent intent = new Intent();
                    intent.putExtras(b);
                    setResult(RESULT_OK, intent);
                    finish();
                }
            }
        });

    }

    @Override
    protected void onDestroy() {
        Log.w("GetSignature", "onDestory");
        super.onDestroy();
    }

    private boolean captureSignature() {

        boolean error = false;
        String errorMessage = "";

        if (error) {
            Toast toast = Toast
                    .makeText(this, errorMessage, Toast.LENGTH_SHORT);
            toast.setGravity(Gravity.TOP, 105, 50);
            toast.show();
        }

        return error;
    }
公共类签名扩展视图{
专用静态最终浮动行程_宽度=5f;
专用静态最终浮动半冲程宽度=冲程宽度/2;
私人油漆=新油漆();
私有路径路径=新路径();
私人浮动lastTouchX;
私密接触;
private final RectF dirtyRect=new RectF();
公共签名(上下文、属性集属性){
超级(上下文,attrs);
paint.setAntiAlias(真);
油漆。设置颜色(颜色。黑色);
绘制.设置样式(绘制.样式.笔划);
绘制.设置行程连接(绘制.连接.圆形);
油漆。设置行程宽度(行程宽度);
}
公共作废保存(视图v){
Log.v(“Log_标签”,“宽度:+v.getWidth());
Log.v(“Log_标签”,“高度:+v.getHeight());
if(mBitmap==null){
mBitmap=Bitmap.createBitmap(mContent.getWidth(),
mContent.getHeight(),Bitmap.Config.RGB_565);
;
}
画布画布=新画布(mBitmap);
试一试{
FileOutputStream mFileOutStream=新的FileOutputStream(mypath);
v、 绘画(画布);
mBitmap.compress(Bitmap.CompressFormat.PNG,90,mFileOutStream);
mFileOutStream.flush();
mFileOutStream.close();
字符串url=Images.Media.insertImage(getContentResolver(),
mBitmap,“title”,null);
Log.v(“Log_标签”,“url:+url”);
//以防您要删除该文件
//布尔删除=mypath.delete();
//Log.v(“Log_标记”,“删除:”+mypath.toString()+deleted);
//如果要将图像转换为字符串,请使用base64
//转换器
}捕获(例外e){
Log.v(“Log_标记”,例如toString());
}
}
公共空间清除(){
path.reset();
使无效();
}
@凌驾
受保护的void onDraw(画布){
画布.绘制路径(路径,绘制);
}
@凌驾
公共布尔onTouchEvent(运动事件){
float eventX=event.getX();
float eventY=event.getY();
mGetSign.setEnabled(true);
开关(event.getAction()){
case MotionEvent.ACTION\u DOWN:
path.moveTo(eventX,eventY);
lastTouchX=eventX;
lastTouchY=eventY;
返回true;
case MotionEvent.ACTION\u移动:
case MotionEvent.ACTION\u UP:
resetDirtyRect(eventX,eventY);
int historySize=event.getHistorySize();
for(int i=0;idirtyRect.right){
dirtyRect.right=historicalX;
}
if(历史目录底部){
dirtyRect.bottom=历史记录;
}
}
私有void resetDirtyRect(float-eventX,float-eventY){
dirtyRect.left=Math.min(lastTouchX,eventX);
dirtyRect.right=Math.max(lastTouchX,eventX);
dirtyRect.top=Math.min(lastTouchY,eventY);
dirtyRect.bottom=Math.max(lastTouchY,eventY);
}
}

我想在位图中保存签名图像当前我可以显示弹出窗口并在其中获取签名,但我不知道如何在位图中获取签名,以便保存到数据库中。

试试这个。它会以位图形式返回通过视图

public class signature extends View {
            private static final float STROKE_WIDTH = 5f;
            private static final float HALF_STROKE_WIDTH = STROKE_WIDTH / 2;
            private Paint paint = new Paint();
            private Path path = new Path();

            private float lastTouchX;
            private float lastTouchY;
            private final RectF dirtyRect = new RectF();

            public signature(Context context, AttributeSet attrs) {
                super(context, attrs);
                paint.setAntiAlias(true);
                paint.setColor(Color.BLACK);
                paint.setStyle(Paint.Style.STROKE);
                paint.setStrokeJoin(Paint.Join.ROUND);
                paint.setStrokeWidth(STROKE_WIDTH);
            }

            public void save(View v) {
                Log.v("log_tag", "Width: " + v.getWidth());
                Log.v("log_tag", "Height: " + v.getHeight());
                if (mBitmap == null) {
                    mBitmap = Bitmap.createBitmap(mContent.getWidth(),
                            mContent.getHeight(), Bitmap.Config.RGB_565);
                    ;
                }
                Canvas canvas = new Canvas(mBitmap);
                try {
                    FileOutputStream mFileOutStream = new FileOutputStream(mypath);

                    v.draw(canvas);
                    mBitmap.compress(Bitmap.CompressFormat.PNG, 90, mFileOutStream);
                    mFileOutStream.flush();
                    mFileOutStream.close();
                    String url = Images.Media.insertImage(getContentResolver(),
                            mBitmap, "title", null);
                    Log.v("log_tag", "url: " + url);
                    // In case you want to delete the file
                    // boolean deleted = mypath.delete();
                    // Log.v("log_tag","deleted: " + mypath.toString() + deleted);
                    // If you want to convert the image to string use base64
                    // converter

                } catch (Exception e) {
                    Log.v("log_tag", e.toString());
                }
            }

            public void clear() {
                path.reset();
                invalidate();
            }

            @Override
            protected void onDraw(Canvas canvas) {
                canvas.drawPath(path, paint);
            }

            @Override
            public boolean onTouchEvent(MotionEvent event) {
                float eventX = event.getX();
                float eventY = event.getY();
                mGetSign.setEnabled(true);

                switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    path.moveTo(eventX, eventY);
                    lastTouchX = eventX;
                    lastTouchY = eventY;
                    return true;

                case MotionEvent.ACTION_MOVE:

                case MotionEvent.ACTION_UP:

                    resetDirtyRect(eventX, eventY);
                    int historySize = event.getHistorySize();
                    for (int i = 0; i < historySize; i++) {
                        float historicalX = event.getHistoricalX(i);
                        float historicalY = event.getHistoricalY(i);
                        expandDirtyRect(historicalX, historicalY);
                        path.lineTo(historicalX, historicalY);
                    }
                    path.lineTo(eventX, eventY);
                    break;

                default:
                    debug("Ignored touch event: " + event.toString());
                    return false;
                }

                invalidate((int) (dirtyRect.left - HALF_STROKE_WIDTH),
                        (int) (dirtyRect.top - HALF_STROKE_WIDTH),
                        (int) (dirtyRect.right + HALF_STROKE_WIDTH),
                        (int) (dirtyRect.bottom + HALF_STROKE_WIDTH));

                lastTouchX = eventX;
                lastTouchY = eventY;

                return true;
            }

            private void debug(String string) {
            }

            private void expandDirtyRect(float historicalX, float historicalY) {
                if (historicalX < dirtyRect.left) {
                    dirtyRect.left = historicalX;
                } else if (historicalX > dirtyRect.right) {
                    dirtyRect.right = historicalX;
                }

                if (historicalY < dirtyRect.top) {
                    dirtyRect.top = historicalY;
                } else if (historicalY > dirtyRect.bottom) {
                    dirtyRect.bottom = historicalY;
                }
            }

            private void resetDirtyRect(float eventX, float eventY) {
                dirtyRect.left = Math.min(lastTouchX, eventX);
                dirtyRect.right = Math.max(lastTouchX, eventX);
                dirtyRect.top = Math.min(lastTouchY, eventY);
                dirtyRect.bottom = Math.max(lastTouchY, eventY);
            }
        }
在必要的地方,比如说

 //where view can be any view.
 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.RGB_565);
    //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;
}

您可以使用

    mGetSign.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            Log.v("log_tag", "Panel Saved");
           //where result is a bitmap which holds passed mView as Bitmap                 
          Bitmap result=getBitmapFromView(mView);
            }
        }
    }); 
公共类CaptureFragment扩展了FragmentActivity{
线性布局内容;
签名;
按钮mClear、mGetSign、mCancel;
公共静态字符串tempDir;
公共整数计数=1;
公共字符串current=null;
私有位图mBitmap;
视图视图;
字符串upLoadServerUri=null;
文件mypath;
私有位图;
私有字符串唯一性;
私人编辑你的名字;
@凌驾
创建时的公共void(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
此.requestWindowFeature(Window.FEATURE\u无\u标题)
 Bitmap bitmap = ((BitmapDrawable)yourView.getDrawable()).getBitmap();
      public class CaptureFragment extends FragmentActivity {


    LinearLayout mContent;
    signature mSignature;
    Button mClear, mGetSign, mCancel;
    public static String tempDir;
    public int count = 1;
    public String current = null;
    private Bitmap mBitmap;
    View mView;
    String upLoadServerUri = null;
    File mypath;


    private Bitmap bitmap;
    private String uniqueId;
    private EditText yourName;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.signature);

        tempDir = Environment.getExternalStorageDirectory() + "/" + getResources().getString(R.string.external_dir) + "/";
        ContextWrapper cw = new ContextWrapper(getApplicationContext());
        File directory = cw.getDir(getResources().getString(R.string.external_dir), Context.MODE_PRIVATE);
        prepareDirectory();
        uniqueId = getTodaysDate() + "_" + getCurrentTime() + "_" + Math.random();
        current = uniqueId + ".png";
        mypath= new File(directory,current);
        //Toast.makeText(CaptureSignature.this, "Path"+mypath, Toast.LENGTH_SHORT).show();

        mContent = (LinearLayout) findViewById(R.id.linearLayout);
        mSignature = new signature(this, null);
        mSignature.setBackgroundColor(Color.WHITE);
        mContent.addView(mSignature, RelativeLayout.LayoutParams.FILL_PARENT, RelativeLayout.LayoutParams.FILL_PARENT);
        //mClear = (Button)findViewById(R.id.clear);
        mGetSign = (Button)findViewById(R.id.getsign);
        mGetSign.setEnabled(false);
        //mCancel = (Button)findViewById(R.id.cancel);
        mView = mContent;

        //yourName = (EditText) findViewById(R.id.yourName);

       /* mClear.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View v)
            {
             finish();
            }
        });*/

        mGetSign.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View v)
            {
                Log.v("log_tag", "Panel Saved");
                boolean error = captureSignature();
                if(!error){
                    mView.setDrawingCacheEnabled(true);
                    mSignature.save(mView);
                    Bundle b = new Bundle();
                    b.putString("status", "done");
                    Intent intent = new Intent();
                    intent.putExtras(b);
                    setResult(RESULT_OK,intent);
                    finish();
                }
            }
        });

        /*mCancel.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Log.v("log_tag", "Panel Canceled");
                Bundle b = new Bundle();
                b.putString("status", "cancel");
                Intent intent = new Intent();
                intent.putExtras(b);
                setResult(RESULT_OK, intent);
                finish();
            }
        });*/


    }

    @Override
    protected void onDestroy() {
        Log.w("GetSignature", "onDestory");
        super.onDestroy();
    }

    private boolean captureSignature() {

        boolean error = false;
        String errorMessage = "";
/*  if(yourName.getText().toString().equalsIgnoreCase("")){
            errorMessage = errorMessage + "Please enter your Name\n";
            error = true;
        }*/



        if(error){
            Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
            toast.setGravity(Gravity.TOP, 75, 50);
            toast.show();
        }

        return error;
    }

    private String getTodaysDate() {

        final Calendar c = Calendar.getInstance();
        int todaysDate =     (c.get(Calendar.YEAR) * 10000) +
                ((c.get(Calendar.MONTH) + 1) * 100) +
                (c.get(Calendar.DAY_OF_MONTH));
        Log.w("DATE:", String.valueOf(todaysDate));
        return(String.valueOf(todaysDate));

    }

    private String getCurrentTime() {

        final Calendar c = Calendar.getInstance();
        int currentTime =     (c.get(Calendar.HOUR_OF_DAY) * 10000) +
                (c.get(Calendar.MINUTE) * 100) +
                (c.get(Calendar.SECOND));
        Log.w("TIME:", String.valueOf(currentTime));
        return(String.valueOf(currentTime));

    }
    private boolean prepareDirectory()
    {
        try
        {
            if (makedirs())
            {
                return true;
            } else {
                return false;
            }
        } catch (Exception e)
        {
            e.printStackTrace();
            Toast.makeText(this, "Could not initiate File System.. Is Sdcard mounted properly?", Toast.LENGTH_SHORT).show();
            return false;
        }
    }

    private boolean makedirs()
    {
        File tempdir = new File(tempDir);
        if (!tempdir.exists())
            tempdir.mkdirs();

        if (tempdir.isDirectory())
        {
            File[] files = tempdir.listFiles();
            for (File file : files)
            {
                if (!file.delete())
                {
                    System.out.println("Failed to delete " + file);
                }
            }
        }
        return (tempdir.isDirectory());
    }

    public class signature extends View
    {
        private static final float STROKE_WIDTH = 5f;
        private static final float HALF_STROKE_WIDTH = STROKE_WIDTH / 2;
        private Paint paint = new Paint();
        private Path path = new Path();
        private float lastTouchX;
        private float lastTouchY;
        private final RectF dirtyRect = new RectF();
        public signature(Context context, AttributeSet attrs)
        {
            super(context, attrs);
            paint.setAntiAlias(true);
            paint.setColor(Color.BLACK);
            paint.setStyle(Paint.Style.STROKE);
            paint.setStrokeJoin(Paint.Join.ROUND);
            paint.setStrokeWidth(STROKE_WIDTH);
        }
        public void save(View v)
        {
            Log.v("log_tag", "Width: " + v.getWidth());
            Log.v("log_tag", "Height: " + v.getHeight());
            if(mBitmap == null)
            {
                mBitmap =  Bitmap.createBitmap (mContent.getWidth(), mContent.getHeight(), Bitmap.Config.RGB_565);;
            }
            Canvas canvas = new Canvas(mBitmap);
            try {
                FileOutputStream mFileOutStream = new FileOutputStream(mypath);
                v.draw(canvas);
                mBitmap.compress(Bitmap.CompressFormat.PNG, 90, mFileOutStream);
                mFileOutStream.flush();
                mFileOutStream.close();
                // String url = MediaStore.Images.Media.insertImage(getContentResolver(), mBitmap, "title", null);
                //  Log.v("log_tag", "url: " + url);
                //Toast.makeText(getApplicationContext(), "URL    :"+mypath.toString(), Toast.LENGTH_SHORT).show();
                //new UploadImage().execute(null);
                //changeStatus();
                // uploadImage();
                //In case you want to delete the file
                //boolean deleted = mypath.delete();
                //Log.v("log_tag","deleted: " + mypath.toString() + deleted);
                //If you want to convert the image to string use base64 converter

            }
            catch(Exception e)
            {
                Log.v("log_tag", e.toString());
            }
        }
        public void clear()
        {
            path.reset();
            invalidate();
        }

        @Override
        protected void onDraw(Canvas canvas)
        {
            canvas.drawPath(path, paint);
        }

        @Override
        public boolean onTouchEvent(MotionEvent event)
        {
            float eventX = event.getX();
            float eventY = event.getY();
            mGetSign.setEnabled(true);

            switch (event.getAction())
            {
                case MotionEvent.ACTION_DOWN:
                    path.moveTo(eventX, eventY);
                    lastTouchX = eventX;
                    lastTouchY = eventY;
                    return true;

                case MotionEvent.ACTION_MOVE:

                case MotionEvent.ACTION_UP:

                    resetDirtyRect(eventX, eventY);
                    int historySize = event.getHistorySize();
                    for (int i = 0; i < historySize; i++)
                    {
                        float historicalX = event.getHistoricalX(i);
                        float historicalY = event.getHistoricalY(i);
                        expandDirtyRect(historicalX, historicalY);
                        path.lineTo(historicalX, historicalY);
                    }
                    path.lineTo(eventX, eventY);
                    break;

                default:
                    debug("Ignored touch event: " + event.toString());
                    return false;
            }

            invalidate((int) (dirtyRect.left - HALF_STROKE_WIDTH),
                    (int) (dirtyRect.top - HALF_STROKE_WIDTH),
                    (int) (dirtyRect.right + HALF_STROKE_WIDTH),
                    (int) (dirtyRect.bottom + HALF_STROKE_WIDTH));

            lastTouchX = eventX;
            lastTouchY = eventY;

            return true;
        }

        private void debug(String string){
        }

        private void expandDirtyRect(float historicalX, float historicalY)
        {
            if (historicalX < dirtyRect.left)
            {
                dirtyRect.left = historicalX;
            }
            else if (historicalX > dirtyRect.right)
            {
                dirtyRect.right = historicalX;
            }

            if (historicalY < dirtyRect.top)
            {
                dirtyRect.top = historicalY;
            }
            else if (historicalY > dirtyRect.bottom)
            {
                dirtyRect.bottom = historicalY;
            }
        }

        private void resetDirtyRect(float eventX, float eventY)
        {
            dirtyRect.left = Math.min(lastTouchX, eventX);
            dirtyRect.right = Math.max(lastTouchX, eventX);
            dirtyRect.top = Math.min(lastTouchY, eventY);
            dirtyRect.bottom = Math.max(lastTouchY, eventY);
        }
    }
}