wangy 发表于 2021-7-1 08:40:53

【lua教程】图片与base64互转


require "import"
import "android.app.*"
import "android.os.*"
import "android.widget.*"
import "android.view.*"
layout={
FrameLayout;

{
    LinearLayout;
    layout_height="match_parent";
    layout_width="match_parent";
    orientation="vertical";
    background=背景色;
    {
      ImageView;
      id="png";
      layout_width="match_parent";
      src="res/Metrial491.png";
      layout_height="30%h";
    };
    {
      EditText;
      hint="Base64码";
   -- MaxLines=6,
      layout_width="match_parent";
      id="ed";
      layout_height="wrap_content";
    };
};


{
    CardView;
    background=次色;
    radius="28dp";
    layout_margin="16dp";
    id="按钮";
    layout_height="56dp";
    CardElevation="4dp";
    layout_gravity="bottom|right";
    layout_width="56dp";
    {
      LinearLayout;
      id="转换";
      layout_height="74dp";
      layout_gravity="center";
      style="?android:attr/buttonBarButtonStyle";
      layout_width="74dp";
      {
      ImageView;
      colorFilter="#ffffffff";
      layout_width="25dp";
      layout_height="25dp";
      layout_gravity="center";
      src="res/swap_horiz_black_24dp.png";
      };
    };
};
};



activity.setTitle("Base64图片互转")
activity.setContentView(loadlayout(layout))

function 图片转base64(bitmap)
local bStream = ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, bStream);
local bytes = bStream.toByteArray();
local txt = Base64.encodeToString(bytes, Base64.DEFAULT);
return txt
end

function base64串转图片(strin)
local bitmapArray = Base64.decode(strin, Base64.DEFAULT);
local bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0,#bitmapArray);
return bitmap
end


转换.onClick=function
if ed.Text=="" then
    png.setDrawingCacheEnabled(true);
    资源 = png.getDrawingCache()
    ed.Text = 图片转base64(资源)
   else
    资源 = base64串转图片(ed.Text)
png.setImageBitmap(资源)
end
end


png.onClick=function
local intent= Intent(Intent.ACTION_PICK)
intent.setType("image/*")
activity.startActivityForResult(intent, 1)
end

function onActivityResult(requestCode,resultCode,intent)
if intent then
    local cursor =this.getContentResolver ().query(intent.getData(), nil, nil, nil, nil)
    cursor.moveToFirst()
    local idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA)
    fileSrc = cursor.getString(idx)
    bit = BitmapFactory.decodeFile(fileSrc)
    png.setImageBitmap(bit)
end
end

页: [1]
查看完整版本: 【lua教程】图片与base64互转