【问题标题】:Create image with text like MEME image and save as a image file.Unable to save image while using Canvas to draw over Bitmap使用 MEME 图像等文本创建图像并保存为图像文件。使用 Canvas 绘制位图时无法保存图像
【发布时间】:2016-01-11 19:40:26
【问题描述】:

我正在创建一个 android 应用程序,它基本上通过 EditTextxml 布局中将背景图像(默认图像)与用户输入合并。 我已经开发了一些工作代码,但它似乎无法正常工作。 欢迎任何形式的帮助。 附言开发新手。

这是我的MainActivity.Java 课程

public class MainActivity extends AppCompatActivity  {

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

EditText editText; //defined edit text
Bitmap bmp; // defined Bitmap
Button button;

public void myBit(){

    bmp = Bitmap.createBitmap(editText.getDrawingCache());
}

public void saveImg()  {

    File myDir = new File("/sdcard/saved_images");
    myDir.mkdir();
    Random ran = new Random();
    int n = 10000;
    n = ran.nextInt(n);
    String fname = "Image-"+n+".jpg";
    File file = new File (myDir, fname);
    if (file.exists ()) file.delete ();
    try {
        FileOutputStream out = new FileOutputStream(file);

        // canvas for merging text over image (Bitmap)
        Canvas canvas = new Canvas(bmp);

        Paint paint = new Paint();
        paint.setColor(Color.WHITE); // Text Color
        paint.setStrokeWidth(12); // Text Size
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_OVER)); // Text Overlapping Pattern
        // some more settings...

        canvas.drawBitmap(bmp, 400, 400, paint); // ◄ Edited here
        canvas.drawText("Testing...", 10, 10, paint);

        bmp.compress(Bitmap.CompressFormat.JPEG, 90, out);
        out.flush();
        out.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

}
@Override

public boolean onCreateOptionsMenu(Menu menu) {

    // Inflate the menu; this adds items to the action bar if it is present.

    //getMenuInflater().inflate(R.menu.main, menu);

    Button button = (Button) findViewById(R.id.button1);

    button.setOnClickListener(new View.OnClickListener() {

        @Override

        public void onClick(View view) {

            saveImg();
            Toast.makeText(MainActivity.this, "Image Saved!!", Toast.LENGTH_SHORT).show();

        }

    });
    return true;
 }
}

【问题讨论】:

  • “sdcard/saved_images”文件夹是否存在?您是否在清单文件中声明了所需的权限?这段代码是否有任何异常?
  • @GilMoshayof 是的,我已经在清单中声明了所有权限,并且这段代码没有出现任何异常。
  • 文件夹呢?它存在吗? mkdir() 返回什么值?
  • @GilMoshayof 是的,该文件夹存在并且它正在创建一个“0 字节”图像文件,只要单击“保存”按钮。
  • 您是否检查过您通过 myBit() 创建的位图的大小?确保它的大小大于 0(宽度和高度)。

标签: java android canvas bitmap


【解决方案1】:

我尝试过以下两种方法从图像上的位图创建文件

  • 一个通过将edittext作为图像或传递视图并从下面发布的代码中获取位图getBitmapFromView方法将视图转换为位图
  • 第二个就像给edittext文本并在默认值之上绘制 image.writeTextOnImage 此方法将从图像上方的给定文本创建位图,它将像 MEME 类型的图像一样工作。用你的图片代替R.drawable.t_img

活动

    public class CreateSaveImage extends AppCompatActivity {
    private EditText editText;
    private File file;
    Bitmap bmp; // defined Bitmap
    ImageView imgShowOuput;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.search_voice);
        file = new File(Environment.getExternalStorageDirectory() + File.separator + "saveimage");
        file.mkdirs();
        editText = (EditText) findViewById(R.id.edtTextView);
        imgShowOuput = (ImageView) findViewById(R.id.imgShowOuput);
        findViewById(R.id.btnSaveImage).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bmp = getBitmapFromView(editText);
                String path = file.getAbsolutePath() + File.separator + System.currentTimeMillis() + "_image" + ".jpg";
                saveBitmapToFile(bmp, path, 100);
                imgShowOuput.setImageBitmap(bmp);
                Toast.makeText(CreateSaveImage.this, "Image Saved!!", Toast.LENGTH_SHORT).show();
            }
        });
        findViewById(R.id.btnSaveImageFromText).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bmp = writeTextOnImage(CreateSaveImage.this, editText.getText().toString());
                String path = file.getAbsolutePath() + File.separator + System.currentTimeMillis() + "_drawImage" + ".jpg";
                saveBitmapToFile(bmp, path, 100);
                imgShowOuput.setImageBitmap(bmp);
            }
        });
    }
    /**
     * @param view
     * @return
     */
    public static Bitmap getBitmapFromView(View view) {
        view.clearFocus();
        view.setPressed(false);
        view.setFocusable(false);
        Bitmap returnedBitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(returnedBitmap);
        Drawable bgDrawable = view.getBackground();
        if (bgDrawable != null)
            bgDrawable.draw(canvas);
        else
            canvas.drawColor(Color.WHITE);
        view.draw(canvas);
        return returnedBitmap;
    }

    public static String saveBitmapToFile(
            Bitmap bitmap, String path, int quality) {
        File imageFile = new File(path);
        OutputStream os;
        try {
            os = new FileOutputStream(imageFile);
            bitmap.compress(Bitmap.CompressFormat.JPEG, quality, os);
            os.flush();
            os.close();
        } catch (Exception e) {
            Log.e("BitmapToTempFile", "Error writing bitmap", e);
        }
        return imageFile.getAbsolutePath();
    }
    public Bitmap writeTextOnImage(Context mContext, String mText) {
        try {
            Resources resources = mContext.getResources();
            float scale = resources.getDisplayMetrics().density;
            /// Here you need to give your default image
            Bitmap bitmap = BitmapFactory.decodeResource(resources, R.drawable.t_img);
            android.graphics.Bitmap.Config bitmapConfig = bitmap.getConfig();
            if (bitmapConfig == null) {
                bitmapConfig = android.graphics.Bitmap.Config.ARGB_8888;
            }
            bitmap = bitmap.copy(bitmapConfig, true);
            Canvas canvas = new Canvas(bitmap);
            Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
            // Change Text Size & Color based on your requirement
            paint.setColor(Color.BLACK);
            paint.setTextSize((int) (21 * scale));
            paint.setShadowLayer(20f, 0, 0, Color.LTGRAY);
            Rect bounds = new Rect();
            paint.getTextBounds(mText, 0, mText.length(), bounds);
            // Change position based on your requirement
            int x = 20;
            int y = 20;
            canvas.drawText(mText, x * scale, y * scale, paint);
            return bitmap;
        } catch (Exception e) {
            return null;
        }
    }
}

Xml 布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/mainlinear"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#7e95e6"
    android:orientation="vertical">

    <EditText
        android:id="@+id/edtTextView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="#FF0000" />

    <Button
        android:id="@+id/btnSaveImage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Save EditText Image" />

    <Button
        android:id="@+id/btnSaveImageFromText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Save Text from EditText as a Image" />

    <ImageView
        android:id="@+id/imgShowOuput"
        android:layout_width="fill_parent"
        android:layout_height="400dp" />
</LinearLayout>

Check output of above which i got

如果有任何事情请告诉我..

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多