Android Studio:将图像保存在SD卡中

时间:2016-08-04 18:29:40

标签: java android

我保留了一个处理ListView的学校项目,其中包含托管在服务器上的图像 当有人从列表中选择一个图像时,这会在另一个布局中以“原始”尺寸显示,即使这里一切都很顺利 但也要问图像显示器何时可以选择将其保存到SD卡中,这是我不能做的部分。

这是我做的代码:

public class MainActivity extends AppCompatActivity {

private ListView listView;
private ProgressDialog progressDialog;
ArrayList asuntos=new ArrayList();
ArrayList imagen=new ArrayList();

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolBar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolBar);
    listView=(ListView) findViewById(R.id.list);
    progressDialog = new ProgressDialog(this);
    progressDialog.setCancelable(false);
    lista o=new lista();
    o.obtenerAvisos();
}

public class lista {

    public void obtenerAvisos() {

        asuntos.clear();
        imagen.clear();

        String tag_string_req = "req_data";

        progressDialog.setMessage("Conectando...");
        showDialog();

        StringRequest strReq = new StringRequest(Request.Method.POST, AppURLs.URL, new Response.Listener<String>() {

            public void onResponse(String response) {

                hideDialog();

                try {

                    JSONArray jsonArray = new JSONArray(response);

                    for (int i = 0; i < jsonArray.length(); i++) {
                        asuntos.add(jsonArray.getJSONObject(i).getString("asunto"));
                        imagen.add(jsonArray.getJSONObject(i).getString("publicacion"));
                    }

                    listView.setAdapter(new ImagenAdaptador(getApplicationContext()));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {

            public void onErrorResponse(VolleyError error) {

                Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
                hideDialog();
            }
        }) {

            protected Map<String, String> getParams() {

                Map<String, String> params = new HashMap<String, String>();
                params.put("tag", "data");
                return params;
            }

        };
        AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
    }
}

private void showDialog() {

    if (!progressDialog.isShowing())
        progressDialog.show();
}

private void hideDialog() {

    if (progressDialog.isShowing())
        progressDialog.dismiss();
}

public class ImagenAdaptador extends BaseAdapter {

    Context ctx;
    LayoutInflater layoutInflater;
    SmartImageView smartImageView;
    TextView tvasunto;

    public ImagenAdaptador(Context applicationContext) {

        this.ctx=applicationContext;
        layoutInflater=(LayoutInflater)ctx.getSystemService(LAYOUT_INFLATER_SERVICE);
    }

    public int getCount() {
        return imagen.size();
    }

    public Object getItem(int position) {
        return position;
    }


    public long getItemId(int position) {
        return position;
    }


    public View getView(int position, View convertView, ViewGroup parent) {

        ViewGroup viewGroup=(ViewGroup) layoutInflater.inflate(R.layout.activity_main_items,null);
        smartImageView=(SmartImageView)viewGroup.findViewById(R.id.imagen1);
        tvasunto=(TextView) viewGroup.findViewById(R.id.tvAsunto);
        final String urlfinal="http://192.168.43.45/InfoTec/publicaciones/"+imagen.get(position).toString();
        Rect rect=new Rect(smartImageView.getLeft(), smartImageView.getTop(), smartImageView.getRight(), smartImageView.getBottom());
        smartImageView.setImageUrl(urlfinal, rect);
        tvasunto.setText(asuntos.get(position).toString());

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(MainActivity.this, Visor.class);
                intent.putExtra("arg", asuntos.get(position).toString());
                intent.putExtra("arg2",imagen.get(position).toString());
                startActivity(intent);
            }
        });
        return viewGroup;
    }
}
}

这部分有效,但这个课程就是问题:

public class Visor extends AppCompatActivity {

TextView tvasunto2;
SmartImageView smartImageView2;
Button descarga;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_visor);
    String original=getIntent().getStringExtra("arg");
    String imgOriginal=getIntent().getStringExtra("arg2");
    tvasunto2=(TextView) findViewById(R.id.tvAsunto2);
    smartImageView2=(SmartImageView) findViewById(R.id.imagen2);
    descarga=(Button) this.findViewById(R.id.button);

    tvasunto2.setText(original);
    String url="http://192.168.43.45/InfoTec/publicaciones/"+imgOriginal;
    Rect rect=new Rect(smartImageView2.getLeft(), smartImageView2.getTop(), smartImageView2.getRight(), smartImageView2.getBottom());
    smartImageView2.setImageUrl(url,rect);

    descarga.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

        }
    });
}
}

如果显示所选图像,但现在不显示如何在下载按钮的情况下处理数据 会有什么解决方案?

2 个答案:

答案 0 :(得分:0)

首先,您需要获取您的位图。您已经可以将它作为对象Bitmap,或者您可以尝试从ImageView获取它,例如:

im=img.resize((height,width), Image.ANTIALIAS);
im=np.array(im);
im=im.ravel();

然后你必须从SD卡到达目录(File对象),例如:

BitmapDrawable drawable = (BitmapDrawable) mImageView1.getDrawable();
Bitmap bitmap = drawable.getBitmap();

接下来,为图像存储创建特定文件:

File sdCardDirectory = Environment.getExternalStorageDirectory();

之后,由于其方法压缩,您只需编写位图,例如:

File image = new File(sdCardDirectory, "test.png");

最后,如果需要,只需处理布尔结果。如:

boolean success = false;

// Encode the file as a PNG image.
FileOutputStream outStream;
try {

    outStream = new FileOutputStream(image);
    bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream); 
    /* 100 to keep full quality of the image */

    outStream.flush();
    outStream.close();
    success = true;
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

请勿忘记在您的清单中添加以下权限:

if (success) {
    Toast.makeText(getApplicationContext(), "Image saved with success",
            Toast.LENGTH_LONG).show();
} else {
    Toast.makeText(getApplicationContext(),
            "Error during image saving", Toast.LENGTH_LONG).show();
}

答案 1 :(得分:0)

最好创建一个对话框让用户选择他们想要存储照片的位置。请记住,有大量 Android 设备,它们可能会有所不同。