单击图像视图(按钮)时如何保存当前显示的图像?

时间:2016-06-14 19:37:16

标签: android image save

我有一个显示10个不同图像的ImageView(你可以刷它们) 我喜欢和不喜欢按钮, 我想实现以下目标:

当我点击图像视图(按钮)将当前显示的图像保存在SD卡中并检索这些保存的图像并将其显示在不同的活动中(在网格视图中)。

我已经阅读了人们如何尝试解决这些问题并且他们通常能够做到的。 但是我的情况有点不同,因为正在显示的图像堆叠在彼此的顶部,我也可以刷它们。

我非常感谢我应该如何面对这个问题的示例代码。

我认为我应该如何面对这个:

> 1. Imageview imageView = (Imageview) findViewById(R.id.imgLike);
> 2. setOnClickListener for the imgLike (this is the imageview "like" button)
> 3. Save the image everytime the user "likes" the image and save it in the SD card
> 4. In the next Activity load the saved images from the SD card and display them in a gridview

我希望在第3步和第4步得到一些帮助。请指出。

我的想法是正确还是我错过了什么?

提前thnx

EDIT.1

package com.example.sick.foodinspiration;

import android.app.Activity;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.Toast;

import com.firebase.client.Firebase;
import com.firebase.tubesock.Base64;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.rk.lib.view.SwipeView;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

public class MainActivity extends Activity implements
        SwipeView.OnCardSwipedListener {

    private final static int CARDS_MAX_ELEMENTS = 5;

    private FrameLayout contentLayout;
    private SwipeView mSwipeView;
    private Firebase mRef;
    public ImageView imageview;

    private int[] meals =                 {
            R.drawable.gevulde_avocados_met_ei,
            R.drawable.pasta_met_spinazie_en_garnalen,
            R.drawable.griekse_aardappelen,
            R.drawable.pasta_met_spinazie_en_gorgonzolasaus,
            R.drawable.zalm_spinazie,
            R.drawable.pasta_bloemkoolsaus,
            R.drawable.paella,
            R.drawable.zweedseballen_salade,
            R.drawable.rode_curry_met_runderreepjes,
            R.drawable.tonijnburger};

    private int count = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_swipe_view_demo);
        contentLayout = (FrameLayout) findViewById(R.id.contentLayout);


        // Add the swipe view
        mSwipeView = new SwipeView(this, R.id.imgSwipeLike, R.id.imgSwipeNope,
                this);
        contentLayout.addView(mSwipeView);

        // Adding the cards initially with the maximum limits of cards.
        for (int i = 0; i < CARDS_MAX_ELEMENTS; i++) {
            addCard(i);
        }
    }

    /**
     * On clicked view.
     *
     * @param clickedView
     *            the clicked view
     */
    public void onClickedView(View clickedView) {
        switch (clickedView.getId()) {
            case R.id.imgDisLike: {
                mSwipeView.dislikeCard();
                break;
            }

            case R.id.imgLike: {

                imageview.setDrawingCacheEnabled(true);
                imageview.buildDrawingCache();
                Bitmap bm=imageview.getDrawingCache();

                OutputStream fOut = null;
                Uri outputFileUri;
                try {
                    File root = new File(Environment.getExternalStorageDirectory()
                            + File.separator + "folder_name" + File.separator);
                    root.mkdirs();
                    File sdImageMainDirectory = new File(root, "myPicName.jpg");
                    outputFileUri = Uri.fromFile(sdImageMainDirectory);
                    fOut = new FileOutputStream(sdImageMainDirectory);
                } catch (Exception e) {
                    Toast.makeText(this, "Error occured. Please try again later.",
                            Toast.LENGTH_SHORT).show();
                }

                try {
                    bm.compress(Bitmap.CompressFormat.PNG, 100, fOut);
                    fOut.flush();
                    fOut.close();
                } catch (Exception e) {

                }
                mSwipeView.likeCard();
                break;
            }
            default:
                break;
        }
    }

    @Override
    public void onLikes() {

        System.out.println("An Card removed");
        // Add a card if you needed after any previous card swiped
        addCard(0);
    }

    @Override
    public void onDisLikes() {
        System.out.println("An Card removed");
        // Add a card if you needed after any previous card swiped
        addCard(0);
    }

    @Override
    public void onSingleTap() {

    }

    /**
     * Adds the card to the swipe.
     */

    private void addCard(int position) {
        final View cardView = LayoutInflater.from(this).inflate(
                R.layout.item_swipe_view, null);
        final ImageView imgMeals = (ImageView) cardView
                .findViewById(R.id.imgMeals);
        imgMeals.setImageResource(meals[count]);
        count++;
        if (count == meals.length) {
            count = 0;
        }
        // Add a card to the swipe view..
        mSwipeView.addCard(cardView, position);

        // Create OnClickListener for the CookBookActivity
        // Declare Button for the Cookbook
        Button btn = (Button) findViewById(R.id.button3);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainActivity.this, CookbookActivity.class));
            }
        });

        // Check Authentication
        mRef = new Firebase(com.example.sick.foodinspiration.Constants.FIREBASE_URL);
        if (mRef.getAuth() == null) {
            loadLoginView();
        }
    }

    private void loadLoginView() {
        Intent intent = new Intent(this, LoginActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
    }

}

更新16-6-2016 我回来了,更新, 我成功地在画廊中添加了一张图片。我曾经遇到过显示 NOT 文件夹的问题,但我修复了它;

            MediaScannerConnection.scanFile(this, new String[] { sdImageMainDirectory.getAbsolutePath() }, null, null);

所以现在我正在寻址的图像被放置在一个新文件夹中。 到目前为止,这么好 问题2 我从可绘制文件夹中获取了5个硬编码图像,并希望在CardView中显示它们。(因此堆叠在彼此的顶部) 然后,我想在按下“喜欢”按钮或使用滑动功能时将这些图像保存在SD卡中。

此问题的相关代码

private int[] meals =                 {
            R.drawable.a,
            R.drawable.b,
            R.drawable.c,
            R.drawable.d,
            R.drawable.e};

    private int count = 0;

private void addCard(int position) {
    final View cardView = LayoutInflater.from(this).inflate(
            R.layout.item_swipe_view, null);
    final ImageView imgMeal = (ImageView) cardView
            .findViewById(R.id.imgMeals);
    imgMeal.setImageResource(meals[count]);
    count++;
    if (count == meals.length) {
        count = 0;
    }
    // Add a card to the swipe view..
    mSwipeView.addCard(cardView, position);

我认为我应该面对的方式如下:

> so *meals* is already being initialized so I dont have to do this.
> I have to make an OnClickListener under the 
private void addCard(int position)
> Implement the code Neo was kind to share with us.
> Put Neo's code in the onClick (Like) function
> Make sure the code listens to "meals" because this is the final ImageView

我希望我正确地看待这个问题。 如果有人可以帮我解决这个问题,我会很感激!

到目前为止,thnx Neo对你有所帮助!

1 个答案:

答案 0 :(得分:0)

试试这段代码:

imageview.setDrawingCacheEnabled(true); //Add this line.
imageview.buildDrawingCache();
Bitmap bm=imageview.getDrawingCache();

将其保存在文件中:

OutputStream fOut = null;
    Uri outputFileUri;
    try {
         File root = new File(Environment.getExternalStorageDirectory()
          + File.separator + "folder_name" + File.separator);
         root.mkdirs();
         File sdImageMainDirectory = new File(root, "myPicName.jpg");
         outputFileUri = Uri.fromFile(sdImageMainDirectory);
         fOut = new FileOutputStream(sdImageMainDirectory);
    } catch (Exception e) {
         Toast.makeText(this, "Error occured. Please try again later.",
         Toast.LENGTH_SHORT).show();
    }

    try {
        bm.compress(Bitmap.CompressFormat.PNG, 100, fOut);
        fOut.flush();
        fOut.close();
    } catch (Exception e) 
}

并且不要忘记在清单中添加权限:

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

希望它会对你有所帮助:)。