我试图将图片保存到外部存储空间(在本例中我使用简单的可绘制资源),但是这个文件并不存在我所做的:重新扫描SD,更改 getExternalStorageDirectory()< / strong>到 getExternalStoragePublicDirectory
它只是不起作用......
我拥有所有权限:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
有一个代码:
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new DrawView(this));
}
class DrawView extends View {
Paint paint;
Bitmap bitmap;
public DrawView(Context context) {
super(context);
paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setTextSize(40);
Bitmap bmpIcon = BitmapFactory.decodeResource(getResources(), R.drawable.launcher);
bmpIcon = Bitmap.createScaledBitmap(bmpIcon, 500, 500, true);
bitmap = Bitmap.createBitmap(500, 500, Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(bitmap);
canvas.drawColor(Color.WHITE);
canvas.drawBitmap(bmpIcon, 0,0, paint);
canvas.drawText("Saved bitmap", 100, 50, paint);
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "savedBitmap.png");
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
} finally {
if (fos != null) fos.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawARGB(80, 102, 204, 255);
canvas.drawBitmap(bitmap, 100, 100, paint);
}
}
}
答案 0 :(得分:0)
文件保存在平板电脑上,内存中有14 api,而且手机没有23 api
您最有可能没有实施runtime permissions。
请注意,如果您查看LogCat,您应该会看到堆栈跟踪显示您无权使用外部存储。