android - 无法在手机内存中保存位图

标签 android bitmap save imageview drawingcache

我在以下代码中得到位图 b 的 java 空异常:我该怎么办? 为什么 getDrawingCache 函数在创建位图时不起作用; 启动操作的按钮的 onClickListener:

KaufenGListener = new OnClickListener() {

            @Override
            public void onClick(View v) {

                Coupon coupon = null;

                System.out.println("-- iv: " + couponView);

                if (clickedcoup == -1) {
                    Toast.makeText(getActivity(), "Please select a coupon", Toast.LENGTH_SHORT).show();
                } else {
                    for (int i = 0; i < coupons.size(); i++) {
                        if (clickedcoup == i) {
                            coupon = coupons.get(i);
                        }
                    }
                    String username;
                    Bitmap coupo = BitmapFactory.decodeResource(getResources(), R.drawable.coupon1);
                    Bitmap barcode = Util.generateEAN("9310779300005", getActivity(), coupo.getWidth() / 3);
                    // Drawable couponDraw = new
                    // BitmapDrawable(getResources(),b);
                    System.out.println("------------b : " + barcode);
                    if (user.address.Nachname != null) {
                        username = user.address.Nachname + " " + user.address.Vorname; // bla
                    } else {
                        username = "";
                    }
                    viewFlipperVino.setDisplayedChild(8);
                    // LayoutParams params = new LayoutParams();
                    // params.width=LayoutParams.MATCH_PARENT;
                    // params.height=(int) (params.width/1.5);

                    //couponView.buildDrawingCache();
                    couponView.setUp(coupo, barcode, coupon.Code, gutscheinName, username, coupon.Wert);
                    clickedcoup = -1;
                    String[] recipients = new String[] { "rosu_alin@ymail.com" };
                    String emailSubject = "Gutschein Schenken fur "+ gutscheinName;
                    String emailText = "Glückwunsch, Sie haben einen Gutschein für Wein & Co!!";
                    Intent intent = new Intent(Intent.ACTION_SEND);
                    intent.setType("plain/text");
                    intent.putExtra(Intent.EXTRA_EMAIL, recipients);
                    intent.putExtra(Intent.EXTRA_SUBJECT, emailSubject);
                    intent.putExtra(Intent.EXTRA_TEXT, emailText);
                    File root = Environment.getExternalStorageDirectory();
                    File file = new File(root, "gutschein.png");
                    try {
                        file.createNewFile();
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }                       
                    couponView.setDrawingCacheEnabled(true);
                    couponView.buildDrawingCache();
                    Bitmap b = couponView.getDrawingCache();
                    System.out.println("bitmapget drawin cache:   "+couponView.getDrawingCache());
                    Saver.saveImg(file, b, getActivity());
                    try {
                        System.out.println("bitmap"+b);
                           FileOutputStream out = new FileOutputStream(file);
                           b.compress(Bitmap.CompressFormat.PNG, 100, out);
                           System.out.println("bitmap.compress"+b.compress(Bitmap.CompressFormat.PNG, 100, out));
                    } catch (Exception e) {
                           e.printStackTrace();
                    }

                    if (!file.exists() || !file.canRead()) {
                        Toast.makeText(getActivity(), "Befestigung Fehler", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    Uri uri = Uri.parse("file://" + file);
                    intent.putExtra(Intent.EXTRA_STREAM, uri);
                    startActivity(Intent.createChooser(intent, "Send email..."));
                }
            }

        };

这是扩展 View 的 CouponView 类: 公共(public)类 CouponView 扩展 View {

private Bitmap coupon, barcode;
Paint paint = new Paint();
Paint paint2 = new Paint();
Paint paint3 = new Paint();
private String name;
private String code;
private String username;
private String wert;
int w;
int h;

public CouponView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    init();
}

public CouponView(Context context, AttributeSet attrs) {
    super(context, attrs);
    init();
}

public CouponView(Context context) {
    super(context);
    init();
}

private void init() {

    paint.setColor(0xFF000000);
    paint.setTextSize(7);
    paint2.setColor(0xFF000000);
    paint2.setTextSize(10);
    paint3.setColor(0xFF000000);
    paint3.setTextSize(25);

}

public void setUp(Bitmap coupon, Bitmap barcode, String code, String name, String username,String wert) {
    this.coupon = coupon;
    this.barcode = barcode;
    this.name = name;
    this.username = username;
    this.code = code;
    this.wert = wert;
     w = coupon.getWidth();
     h = coupon.getHeight();
    System.out.println("height"+h);
    System.out.println("width"+w);

    invalidate();
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    System.out.println("-------------CouponView.onDraw()");
    canvas.drawBitmap(coupon, 0, 0, null);
    canvas.drawBitmap(barcode, w/1.61f, h/1.20f, null);
    canvas.drawText("9310779300005", w/1.429f, h/1.018f, paint);
    canvas.drawText("9310779300005", w/18.12f , h/1.073f, paint2);
    canvas.drawText(code, w/1.8875f, h/1.073f, paint2);
    canvas.drawText(username, w/11.32f, h/10.3f, paint2);
    canvas.drawText(name, w/11.32f, h/5.936f, paint2);
    canvas.drawText(wert, w/1.294f, h/1.641f, paint3);
}
}

按照我的逻辑,我将 couponView 的绘图缓存设置为 (true),然后我开始构建绘图缓存。然后我启动位图 getDrawingCache()。仅此一项就可以保存我的文件。我错过了什么? 此外,Saves.saveIMG 函数与它之后的 try catch 做同样的事情(我只是从同事那里拿来的,因为它更有条理。而且我虽然它使用 imageView 来保存,而不是位图。

public class Saver {
public static void saveImg(File pic, Bitmap picture,Context context) {
    folderExists(pic);
    try {
        FileOutputStream out = new FileOutputStream(pic);
        picture.compress(Bitmap.CompressFormat.JPEG, 100, out);
        Log.i(Saver.class.toString(), " picture writed at: " + pic.getAbsolutePath());
        Toast.makeText(context, "pic saved", Toast.LENGTH_SHORT).show();
    } catch (Exception e) {
        pic.delete();
        Log.i(Saver.class.toString(), " picture writing error: " + e.getMessage());
        Toast.makeText(context, "pic not saved", Toast.LENGTH_SHORT).show();
    }
}

private static void folderExists(File dir) {
    System.out.println("-=-=- : " + dir.getAbsolutePath());
    if (!dir.getParentFile().exists()) {
        dir.mkdirs();
    }

}

最佳答案

不确定您的代码究竟有什么问题,但这对我来说可以从手机内存中保存和读取位图:

将Bitmap写入内存:

public void writeBitmapToMemory(String filename, Bitmap bitmap) {
        FileOutputStream fos;
        // Use the compress method on the Bitmap object to write image to the OutputStream
        try {
            fos = this.openFileOutput(filename, Context.MODE_PRIVATE);
            // Writing the bitmap to the output stream
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
            fos.close();

        } 
        catch (FileNotFoundException e) {
            e.printStackTrace();


        } 
        catch (IOException e) {
            e.printStackTrace();


        }

    }

阅读:

public Bitmap readBitmapFromMemory(String filename) {
        Bitmap defautBitmap = null;
        File filePath = this.getFileStreamPath(filename);
        FileInputStream fi;
        try {
            fi = new FileInputStream(filePath);
            defautBitmap = BitmapFactory.decodeStream(fi);

        } 
        catch (FileNotFoundException e) {
            e.printStackTrace();

        }

        return defautBitmap;

    }

希望对您有所帮助。

关于android - 无法在手机内存中保存位图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11989785/

相关文章:

android - 将可绘制对象转换为字符串以传递给另一个 Activity

java - 如何创建 ArrayList 的安全保存并在类被编辑时加载它?

java - 我正在尝试制作一个程序,将对象保存到文件中,然后从文件中读取对象。我究竟做错了什么?

android - 未显示所有数据,但带有 RecyclerView 的 AdMobs

android - CardView 未显示在 RecyclerView 中

java - 如何在渲染 View 之前对其进行屏幕截图或快照?

android - 用 setImageBitmap 替换对 setImageResource() 的调用以减少打嗝?

swift - 如何确保在数据加载之前我不会访问数据?

Android 应用使用 Games.getGamesServerAuthCode 从 Oauth 2.0 客户端获取授权码

android - 高效适配器有java.lang.ClassCastException?