在android中将两个图像保存为单个图像

Save two images as a single image in android(在android中将两个图像保存为单个图像)

本文介绍了在android中将两个图像保存为单个图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

I have an image view in android and on that image view i have another image view.. Both image views contain two different images.. Now i want to save it as a single JPG image in my phone gallery.. So how can i do that?? I tried some code but it is not working.

Here is my code.

XML File:

    <ImageView
        android:id="@+id/innerImage"
        android:layout_width="300dp"
        android:layout_height="230dp"
        android:layout_centerInParent="true"
        android:layout_centerVertical="true"
        android:contentDescription="@android:string/untitled" 
        android:background="@drawable/white"/>

    <Button
        android:id="@+id/btnselectPhoto"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/ivImage"
        android:layout_alignLeft="@+id/ivImage"
        android:layout_marginBottom="16dp"
        android:text="@string/select_photo" />

    <ImageView
        android:id="@+id/ivImage"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"
        android:contentDescription="@android:string/untitled" />

    <Button
        android:id="@+id/btnsave"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@id/btnselectPhoto"
        android:layout_alignBottom="@id/btnselectPhoto"
        android:layout_alignRight="@+id/ivImage"
        android:layout_marginLeft="32dp"
        android:layout_toRightOf="@id/btnselectPhoto"
        android:text="@string/save" />

And here is my Java Code:

public class MainActivity extends ActionBarActivity {

    private static String mTempDir;
    Bitmap mBackImage, mTopImage, mBackground, mNewSaving;
    Canvas mComboImage;
    FileOutputStream mFileOutputStream;
    BitmapDrawable mBitmapDrawable;
    private String mCurrent = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Call method for selecting Image
        SelectImage();
    }

    // method for selecting image
    private void SelectImage() {
        // items to put in alert box
        final CharSequence[] items = { "Take Photo", "Choose from Library", "Cancel" };

        // Alert box
        final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setTitle("Add Photo");

        // Click Event of button
        Button btn = (Button) findViewById(R.id.btnselectPhoto);
        btn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // Set items in alert box
                builder.setItems(items, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int item) {
                        // Start Camara
                        if (items[item].equals("Take Photo")) {
                            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                            File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
                            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));

                            startActivityForResult(intent, 1);
                        }
                        // Open Gallery
                        else if (items[item].equals("Choose from Library")) {
                            Intent intent = new Itent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                            intent.setType("image/*");
                            startActivityForResult(intent, 2);
                        }
                        // Cancel code
                        else if (items[item].equals("Cancel")) {
                            dialog.dismiss();
                        }
                    }
                });
                builder.show();
            }
        });
    }

    // This method is called for setting image in imageview.
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        final String picturePath;
        ImageView iv = (ImageView) findViewById(R.id.innerImage);

        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 1) {
                File f = new File(Environment.getExternalStorageDirectory().toString());
                for (File temp : f.listFiles()) {
                    if (temp.getName().equals("temp.jpg")) {
                        f = temp;
                        break;
                    }
                }
                try {
                    Bitmap bm;
                    BitmapFactory.Options btmapOptions = new BitmapFactory.Options();
                    bm = BitmapFactory.decodeFile(f.getAbsolutePath(), btmapOptions);
                    // bm = Bitmap.createScaledBitmap(bm, 70, 70, true);

                    iv.setImageBitmap(bm);

                    String path = android.os.Environment.getExternalStorageDirectory() + File.separator + "Phoenix" + File.separator + "default";
                    f.delete();
                    OutputStream fOut = null;
                    File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
                    try {
                        fOut = new FileOutputStream(file);
                        bm.compress(Bitmap.CompressFormat.JPEG, 85, fOut);
                        fOut.flush();
                        fOut.close();
                    }
                    catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                    catch (IOException e) {
                        e.printStackTrace();
                    }
                    catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                catch (Exception e) {
                    e.printStackTrace();
                }
            }
            else if (requestCode == 2) {
                Uri selectedImage = data.getData();
                String[] filePathColumn = { MediaStore.Images.Media.DATA };
                Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
                cursor.moveToFirst();
                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                picturePath = cursor.getString(columnIndex);
                cursor.close();
                // Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
                iv.setImageBitmap(BitmapFactory.decodeFile(picturePath));
                saveimage(picturePath);
            }
        }
    }

    private void saveimage(String imgPath) {
        mTempDir = Environment.getExternalStorageDirectory() + "/" + "Demo" + "/";
        File mTempFile = new File(mTempDir);
        if (!mTempFile.exists()) {
            mTempFile.mkdirs();
        }
        mCurrent = "temp.png";

        mBackground = Bitmap.createBitmap(604, 1024, Bitmap.Config.ARGB_8888);
        mBackImage = BitmapFactory.decodeResource(getResources(), R.drawable.image1);
        mTopImage = BitmapFactory.decodeFile(imgPath);
        mComboImage = new Canvas(mBackground);
        mComboImage.drawBitmap(mBackImage, 0f, 0f, null);
        mComboImage.drawBitmap(mTopImage, 0f, 0f, null);

        Button savebtn = (Button) findViewById(R.id.btnsave);
        savebtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                try {
                    mBitmapDrawable = new BitmapDrawable(getResources(), mBackground);
                    mNewSaving = ((BitmapDrawable) mBitmapDrawable).getBitmap();
                    String FtoSave = mTempDir + mCurrent;
                    File mFile = new File(FtoSave);
                    mFileOutputStream = new FileOutputStream(mFile);
                    mNewSaving.compress(CompressFormat.PNG, 95, mFileOutputStream);
                    mFileOutputStream.flush();
                    mFileOutputStream.close();
                }
                catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}

解决方案

I worked on a similar issue once, and i solved it by putting both images in the same linear layout an creating Bitmap from that layout. Than you can just write a function to save that Bitmap where ever you want.

Here's some sample code:

private Bitmap getBitmap(View v) {
    v.clearFocus();
    v.setPressed(false);

    boolean willNotCache = v.willNotCacheDrawing();
    v.setWillNotCacheDrawing(false);

    // Reset the drawing cache background color to fully transparent
    // for the duration of this operation
    int color = v.getDrawingCacheBackgroundColor();
    v.setDrawingCacheBackgroundColor(0);

    if (color != 0) {
        v.destroyDrawingCache();
    }
    v.buildDrawingCache();
    Bitmap cacheBitmap = v.getDrawingCache();
    if (cacheBitmap == null) {
        Toast.makeText(StopWarApp.getContext(), "Something went wrong",
                Toast.LENGTH_SHORT).show();
        return null;
    }

    Bitmap bitmap = Bitmap.createBitmap(cacheBitmap);

    // Restore the view
    v.destroyDrawingCache();
    v.setWillNotCacheDrawing(willNotCache);
    v.setDrawingCacheBackgroundColor(color);

    return bitmap;
}

这篇关于在android中将两个图像保存为单个图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:在android中将两个图像保存为单个图像

基础教程推荐