我正在研究一个模因发生器。目前,我正在尝试从设备上传照片,以通过Canvas
在照片上添加标题,并通过在其中创建新文件夹将新位图保存到设备的“图库”应用中。这是我的尝试:
public void createBitmapAndSave(ImageView img){
BitmapDrawable bitmapDrawable = ((BitmapDrawable) img.getDrawable());
Bitmap bitmap = bitmapDrawable.getBitmap();
Bitmap mutableBitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);
Canvas canvas = new Canvas(mutableBitmap);
Paint paint = new Paint();
String topText = topTextView.getText().toString();
String bottomText = bottomTextView.getText().toString();
canvas.drawText(topText, 0, 0, paint);
canvas.drawText(bottomText, 50, 50, paint);
File file;
String path = Environment.getExternalStorageDirectory().toString();
file = new File(path, "Meme" + ".jpg");
try{
OutputStream stream = null;
stream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG,100,stream);
stream.flush();
stream.close();
}catch (IOException e){ e.printStackTrace(); }
}
然后我在BroadcastReceiver
中调用该方法:
private BroadcastReceiver listener = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent ) {
String data = intent.getStringExtra("DATA");
Toast.makeText(context, data + " received", Toast.LENGTH_SHORT).show();
createBitmapAndSave(imageView);
}
};
此刻,我什至不确定编辑或保存位图是否还能正常工作,因为我无法在应用程序的文件夹中找到它。
更新
我找到了问题。我决定在try / catch块中放置一条Toast消息,以查看流是否在正常工作,因为在该流不在try / catch块之外之前,我会在每次运行时看到它。这就是我所做的:
public void createBitmapAndSave(ImageView img){
BitmapDrawable bitmapDrawable = ((BitmapDrawable) img.getDrawable());
Bitmap bitmap = bitmapDrawable.getBitmap();
Bitmap mutableBitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);
Canvas canvas = new Canvas(mutableBitmap);
Paint paint = new Paint();
String topText = topTextView.getText().toString();
String bottomText = bottomTextView.getText().toString();
canvas.drawText(topText, 0, 0, paint);
canvas.drawText(bottomText, 50, 50, paint);
File file;
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsolutePath();
file = new File(path, "Meme" + ".jpg");
try{
OutputStream stream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG,100,stream);
stream.flush();
stream.close();
Toast.makeText(getContext(), path, Toast.LENGTH_SHORT).show();
}catch (IOException e){ e.printStackTrace();}
}
现在,我根本看不到烤面包消息。似乎流甚至无法正常工作,但我不明白为什么它不能。
答案 0 :(得分:1)
请勿使用String path = Environment.getExternalStorageDirectory().toString();
它将把您的文件存储在用户不可见的私有存储中。
使用File path = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);