我在这里有一个FileOutputstream
:
public void SaveImage(Bitmap default_b) {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/saved_images");
myDir.mkdirs();
Random generator = new Random();
int n = 100000;
n = generator.nextInt(n);
String fname = "Image-" + n +".jpg";
File file = new File (myDir, fname);
if (file.exists()) file.delete();
try {
FileOutputStream out = openFileOutput("file", Context.MODE_WORLD_WRITEABLE);
default_b.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
但我在这一行上收到错误:
FileOutputStream out = openFileOutput("file", Context.MODE_WORLD_WRITEABLE);
说openFileOutput是未定义的*(请注意,这是在基本适配器类中,当我尝试从上下文中执行此操作时,Context.getApplicationContext().openFileOutput
会收到错误“无法对非静态方法getApplicationContext()来自类型Context“)我还得到了不推荐使用Context.MODE_WORLD_WRITABLE的警告。
然后我在这里有我的FileInputstream(在另一个扩展BaseAdapter的类中):
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// Try to reuse the views
ImageView view = (ImageView) convertView;
// if convert view is null then create a new instance else reuse it
if (view == null) {
view = new ImageView(mContextGV);
Log.d("GridViewAdapter", "new imageView added");
}
try {
FileInputStream in = new openFileInput("file");
BufferedInputStream buf = new BufferedInputStream(in);
byte[] bitMapA = new byte[buf.available()];
buf.read(bitMapA);
Bitmap bM = BitmapFactory.decodeByteArray(bitMapA, 0, bitMapA.length);
view.setImageBitmap(bM);
if (in != null) {
in.close();
}
if (buf != null) {
buf.close();
}
} catch (Exception e) {
e.printStackTrace();
}
view.setImageResource(drawables.get(position));
view.setScaleType(ImageView.ScaleType.CENTER_CROP);
view.setLayoutParams(new android.widget.GridView.LayoutParams(70, 70));
view.setTag(String.valueOf(position));
return view;
}
这一行有错误:
FileInputStream in = new openFileInput("file");
说openFileInput是未定义的,当我将其更改为:
时再次FileInputStream in = new Context.getApplicationContext().openFileInput("file");
我收到一条错误消息,说“Context.getApplicationContext()无法解析为类型”
答案 0 :(得分:0)
尝试替换文件OutputStream代码
String fname = "Image-" + n ;
File file = new File (myDir, fname);
if (file.exists()) file.delete();
try {
File f = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
+ "/" + fname +".png");
FileOutputStream fos = new FileOutputStream(f);
default_b.compress(Bitmap.CompressFormat.PNG,90,fos);
} catch (Exception e) {
e.printStackTrace();
}
它的作品非常适合我保存图像