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

时间:2014-08-29 13:27:18

标签: android imageview android-gallery

我在Android中有一个图像视图,在该图像视图上我有另一个图像视图..两个图像视图包含两个不同的图像..现在我想将它保存为我的手机库中的单个JPG图像..那么如何我可以那样做吗? 我尝试了一些代码,但它没有用。

这是我的代码。

XML文件:

    <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" />

这是我的Java代码:

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();
                }
            }
        });
    }
}

3 个答案:

答案 0 :(得分:1)

我曾经在类似的问题上做过一次,我通过将两个图像放在相同的线性布局中来解决它,从而创建了该布局的Bitmap。你可以编写一个函数来保存那个你想要的Bitmap。

以下是一些示例代码:

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;
}

答案 1 :(得分:0)

    public void combineImages(Bitmap c, Bitmap s,String loc) { 
    Bitmap cs = null; 

    int width, height = 0; 

    if(c.getWidth() > s.getWidth()) { 
      width = c.getWidth(); 
      height = c.getHeight() + s.getHeight(); 
    } else { 
      width = s.getWidth(); 
      height = c.getHeight() + s.getHeight(); 
    } 

    cs = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); 

    Canvas comboImage = new Canvas(cs); 

    comboImage.drawBitmap(c, 0f, 0f, null); 
    comboImage.drawBitmap(s, 0f, c.getHeight(), null); 


    String tmpImg = String.valueOf(System.currentTimeMillis()) + ".png"; 

    OutputStream os = null; 
    try { 
      os = new FileOutputStream(loc + tmpImg); 
      cs.compress(CompressFormat.PNG, 100, os); 
    } catch(IOException e) { 
      Log.e("combineImages", "problem combining images", e); 
    }

  } 

您可以使用此组合两个位图。

答案 2 :(得分:0)

  LinearLayout ll;
@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);

    setContentView(R.layout.layout2);
   ll=(LinearLayout)findViewById(R.id.linearlayout);

 //Add button in your layout and write the below code onclick of button.
button.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View arg0) {

    ll.setDrawingCacheEnabled(true);
    Bitmap bitmap = ll.getDrawingCache();

    String root = Environment.getExternalStorageDirectory().toString();
    File newDir = new File(root + "/saved_picture");
    newDir.mkdirs();
    Random gen = new Random();
    int n = 10000;
    n = gen.nextInt(n);
    String fotoname = n + ".jpg";
    File file = new File(newDir, fotoname);
    String s = file.getAbsolutePath();
    System.err.print("Path of saved image." + s);

    try {
        FileOutputStream out = new FileOutputStream(file);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
        out.flush();
        out.close();
    } catch (Exception e) {

    }
        }
     });