实现图片添加文字水印

记录一个给图片添加文字水印的方法。
整体布局:在Imageview上自己想要的位置覆盖一个TextView,可以手动输入文字,并将添加文字后的图片保存到本地图册。
Xml文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/sour_pic_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="原图" />

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="200dp">

        <ImageView
            android:id="@+id/sour_pic"
            android:layout_width="match_parent"
            android:layout_height="200dp"
            android:scaleType="centerInside" />   //初始图片 

        <TextView
            android:id="@+id/edit"
            android:layout_width="match_parent"
            android:layout_marginLeft="50dp"
            android:layout_marginRight="50dp"
            android:layout_height="50dp"
            android:hint="请输入内容"
            android:textColorHint="@color/colorWhite"
            android:gravity="center"
            android:textSize="50px"
            android:textColor="@color/colorWhite"
            android:singleLine="true"
            android:ellipsize="end"
            android:background="@null"
            android:textCursorDrawable="@null"
            android:layout_alignParentBottom="true"
            android:layout_centerHorizontal="true"
            android:layout_marginBottom="40px" />   //图片上的文字展示框
    </RelativeLayout>


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <Button
            android:id="@+id/subtitle"
            android:layout_width="wrap_content"
            android:layout_weight="1"
            android:text="加字幕"
            android:layout_height="wrap_content" />  

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="3"
            android:text="刷新截屏"/>

        <Button
            android:id="@+id/save"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="保存"/>
    </LinearLayout>



    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        
        <ImageView
            android:id="@+id/wartermark_pic"
            android:layout_width="wrap_content"
            android:layout_weight="1"
            android:layout_height="200dp"
            android:scaleType="centerInside"/>  //显示添加水印后的图片

        <ImageView
            android:id="@+id/wartermark_pic2"
            android:layout_width="wrap_content"
            android:layout_weight="1"
            android:layout_height="200dp"
            android:scaleType="centerInside"/>
    </LinearLayout>


        <ScrollView
            android:id="@+id/scrollview"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentStart="true"
            android:layout_alignParentBottom="true"
            android:visibility="invisible"
            android:layout_marginStart="0dp">  //便于软件盘弹出时位置变化

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal">

                <EditText
                    android:id="@+id/edit_text"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_weight="15"
                    android:background="@drawable/edit_bg"
                    android:hint="请输入内容" />        //输入文字框

                <Button
                    android:id="@+id/finish"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:text="完成" />

            </LinearLayout>
        </ScrollView>

    </RelativeLayout>


</LinearLayout>

封装图片处理类,给图片添加文字水印,直接调用。

package com.sylincom.voicecontrol;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;

public class ImageUtils {

    private static final String Tag = "ImageUtils" ;
    
    /**
     * 绘制文字到中间
     * @param context
     * @param bitmap
     * @param text
     * @param size
     * @param color
     * @return
     */
    public static Bitmap drawTextToCenter(Context context, Bitmap bitmap, String text,
                                          int size, int color) {
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setColor(color);
        paint.setTextSize(dp2px(context, size));
        Rect bounds = new Rect();
        paint.getTextBounds(text, 0, text.length(), bounds);
        return drawTextToBitmap(context, bitmap, text, paint, bounds,
                (bitmap.getWidth() - bounds.width()) / 2,
                (bitmap.getHeight() - bounds.height()) / 1.1);
}

    //图片上绘制文字
    private static Bitmap drawTextToBitmap(Context context, Bitmap bitmap, String text,
                                           Paint paint, Rect bounds, int paddingLeft, double paddingTop) {
        android.graphics.Bitmap.Config bitmapConfig = bitmap.getConfig();

        paint.setDither(true); // 获取更清晰的图像采样
        paint.setFilterBitmap(true);// 过滤一些
        if (bitmapConfig == null) {
            bitmapConfig = android.graphics.Bitmap.Config.ARGB_8888;
        }
        bitmap = bitmap.copy(bitmapConfig, true);
        Canvas canvas = new Canvas(bitmap);

        canvas.drawText(text, paddingLeft, (float) paddingTop, paint);
        return bitmap;
    }
    
    /**
     * dip转pix
     * @param context
     * @param dp
     * @return
     */
    public static int dp2px(Context context, float dp) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dp * scale + 0.5f);
    }

}

ScreenshotsActivity:实现添加文字水印

package com.sylincom.voicecontrol;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.UUID;

public class ScreenshotsActivity extends AppCompatActivity implements View.OnClickListener{

    private static final String Tag = "ScreenshotsActivity" ;
    private ImageView mSourImage;
    private ImageView mWartermarkImage;
    private EditText editText_input;
    private TextView textView;
    private String edit;
    private Button subtitle ,finish,save;
    private Bitmap sourBitmap ,textBitmap;
    private ScrollView scrollView;
    private String dir ,filename;
    private File file;
    private FileOutputStream out = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_screenshots);

        editText_input = findViewById(R.id.edit_text); //底部输入框
        textView = findViewById(R.id.edit); //图片上文字框
        subtitle = findViewById(R.id.subtitle); //添加字幕按钮
        save = findViewById(R.id.save); //保存图片按钮
        finish = findViewById(R.id.finish); //底部输入框完成按钮
        scrollView = findViewById(R.id.scrollview);
        mSourImage = findViewById(R.id.sour_pic);//原图片
        mWartermarkImage = findViewById(R.id.wartermark_pic);//添加水印后的图片
        
        //原始画布
        sourBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.bg03);
        mSourImage.setImageBitmap(sourBitmap);

        //定义文件保存路径
        dir =  Environment.getExternalStorageDirectory().getAbsolutePath() + "/Screenshots/";

        subtitle.setOnClickListener(this);
        save.setOnClickListener(this);
        finish.setOnClickListener(this);
    }

    //启动activity方法
    public static void actionStart(Context context){
        Intent intent = new Intent(context, ScreenshotsActivity.class);
        context.startActivity(intent);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.subtitle:
                scrollView.setVisibility(View.VISIBLE); //设置输入文字框可见
                //设置软键盘弹出
                InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
                imm.toggleSoftInput(0, InputMethodManager.RESULT_SHOWN);
                //清空之前输入的内容
                editText_input.getText().clear();
                //添加监听事件,将输入内容实时传递到TextView中
                editText_input.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {
                        textView.setText(editText_input.getText().toString());
                    }

                    @Override
                    public void afterTextChanged(Editable s) {

                    }
                });
                break;
            case R.id.finish:
                textView.setText(editText_input.getText().toString());
                //控制显示文字的长度
                if(textView.getText().length() <= 21){
                    edit = textView.getText().toString();
                }else {
                    edit = textView.getText().toString().substring(0,21) + "...";
                }
                int size1 = (int) textView.getTextSize();
                //调用方法 实现新的水印图片
                textBitmap = ImageUtils.drawTextToCenter(ScreenshotsActivity.this, sourBitmap, edit, size1, Color.WHITE);
                scrollView.setVisibility(View.INVISIBLE);
                //设置软键盘消失
                InputMethodManager imm1 = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
                imm1.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
                break;
            case R.id.save:
                //获取内部存储状态
                String state = Environment.getExternalStorageState();
                //如果状态不是mounted,无法读写
                if (!state.equals(Environment.MEDIA_MOUNTED)) {
                    return;
                }
                mWartermarkImage.setImageBitmap(textBitmap);
                scrollView.setVisibility(View.INVISIBLE);
                //通过UUID生成字符串文件名
                filename = UUID.randomUUID().toString();
                file = new File(dir + filename + ".jpg");
                try {
                    out = new FileOutputStream(file);
                    textBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
                    out.flush();
                    out.close();
                    Toast.makeText(this,"保存成功",Toast.LENGTH_SHORT).show();
                    //保存图片后发送广播通知更新数据库
                    Uri uri = Uri.fromFile(file);
                    sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
                } catch (FileNotFoundException e) {
                    Log.e(Tag,"out");
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值