【问题标题】:Cannot save bitmap on phone memory无法将位图保存在手机内存中
【发布时间】:2012-08-16 14:46:47
【问题描述】:

我在以下代码中得到位图 b 的 java null 异常:我该怎么办? 为什么 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 类: 公共类 CouponView 扩展视图 {

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();
    }

}

【问题讨论】:

  • 哪行代码抛出了NullPointerException
  • b.compress(Bitmap.CompressFormat.PNG, 100, out);
  • 但是 System.out.prinln("bitmap=",b);行返回位图=空,所以我猜是位图 b 是问题,因为 getDrawingCache 没有加载它
  • 嗯? System.out.println 在 android 中什么都不做,stackoverflow.com/questions/2220547/…
  • 我的,观察你的 LogCat,看看 Syso 写在那里

标签: android bitmap save imageview drawingcache


【解决方案1】:

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

将位图写入内存:

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;

    }

我希望这会有所帮助。

【讨论】:

  • 问题是位图从一开始就是空的。所以我认为我做的那部分代码没问题,或者至少它没有错误。我的代码的问题是从 imageView (couponView) 获取位图。那边出了点问题,没有正确创建我的位图
【解决方案2】:

我首先创建了一个空位图,并将其用作画布进行绘制。 代码:

couponView.setDrawingCacheEnabled(true);
  couponView.buildDrawingCache();
  couponView.setUp(coupo, barcode, coupon.Code, gutscheinName, username, coupon.Wert);
  Bitmap b = Bitmap.createBitmap(couponView.w, couponView.h, 
                            Config.ARGB_8888);
  Canvas canvas = new Canvas(b);
  couponView.draw(canvas);
  Saver.saveImg(file, b, getActivity());
  Uri uri = Uri.parse("file://" + file);
  intent.putExtra(Intent.EXTRA_STREAM, uri);
  startActivity(Intent.createChooser(intent, "Send email..."));

【讨论】:

    猜你喜欢
    • 2018-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-10
    相关资源
    最近更新 更多