Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 如何在从库中选择图像时裁剪图像?_Android_Kotlin_Retrofit_Retrofit2_Crop - Fatal编程技术网

Android 如何在从库中选择图像时裁剪图像?

Android 如何在从库中选择图像时裁剪图像?,android,kotlin,retrofit,retrofit2,crop,Android,Kotlin,Retrofit,Retrofit2,Crop,我指的是这个教程--> 本教程仅用于从gallery中选择图像,而不进行裁剪 实际上,我的想法是从图库中选择具有裁剪功能的图像,然后使用改装贴子上传该图像,您可以在我的代码中找到该贴子-->这是在裁剪功能之外实现的 唯一剩下的就是修剪……我需要帮助 以下是我目前的代码--> class-EditProfile:AppCompatActivity(){ 专用val图像=100 变量位图:位图?=null 变量配置文件:ImageView?=null 重写创建时的乐趣(savedInstanceSt

我指的是这个教程-->

本教程仅用于从gallery中选择图像,而不进行裁剪

实际上,我的想法是从图库中选择具有裁剪功能的图像,然后使用改装贴子上传该图像,您可以在我的代码中找到该贴子-->这是在裁剪功能之外实现的

唯一剩下的就是修剪……我需要帮助

以下是我目前的代码-->

class-EditProfile:AppCompatActivity(){
专用val图像=100
变量位图:位图?=null
变量配置文件:ImageView?=null
重写创建时的乐趣(savedInstanceState:Bundle?){
super.onCreate(savedInstanceState)
setContentView(R.layout.editprofile)
var mActionBarToolbar=findviewbyd(R.id.toolbatable);
设置支持操作栏(mActionBarToolbar);
//将返回箭头添加到工具栏
如果(getSupportActionBar()!=null){
getSupportActionBar()?.setDisplayHomeAsUpEnabled(true);
getSupportActionBar()?.setDisplayShowHomeEnabled(true);
getSupportActionBar()?.setHomeAsUpIndicator(R.drawable.ic键盘箭头左箭头黑色24dp);
getSupportActionBar()?.setDisplayShowTitleEnabled(false);
//supportActionBar?.setTitle(“表格”)
//getSupportActionBar()?.setTitle((Html.fromHtml(“+getString(R.string.Myaccount)+”);
}
val myCalendar:Calendar=Calendar.getInstance()
val edittext1=findViewById(R.id.dob)作为EditText
val日期=
OnDateSetListener{view,year,monthOfYear,dayOfMonth->//TODO自动生成的方法存根
myCalendar.set(Calendar.YEAR,YEAR)
myCalendar.set(Calendar.MONTH,MonthHofYear)
myCalendar.set(Calendar.DAY\u OF\u MONTH,dayOfMonth)
val myFormat=“dd-MM-yyyy”//您需要将其放在此处
val sdf=SimpleDataFormat(myFormat,Locale.US)
edittext1.setText(sdf.format(myCalendar.getTime())}
edittext1.setOnClickListener(对象:View.OnClickListener{
覆盖有趣的onClick(v:视图?){
//TODO自动生成的方法存根
日期选择器对话框(
this@EditProfile,日期,我的日历
.get(日历.年),myCalendar.get(日历.月),
myCalendar.get(Calendar.DAY\u OF\u MONTH)
).show()
}
})
val edit=edittext1.text
profile=findviewbyd(R.id.profilepic)作为ImageView
val token:String=SharedPrefManager.getInstance(applicationContext).user.access\u token.toString()
更新client.instance.fetchUser(令牌)
.enqueue(对象:回调{
覆盖失效时的乐趣(调用:调用,t:可丢弃){
Log.d(“res”和“+t”)
}
覆盖响应(
呼叫:呼叫,,
答复:答复
) {
var res=响应
if(res.body()?.status==200){
//val retro:List=response.body().getData()
val retro:Myaccount_data=res.body()!!.data
val retro1:User_data=retro.User_data
使用(applicationContext.load)滑动(1.profile\u pic)
.diskCacheStrategy(diskCacheStrategy.ALL)
.占位符(R.drawable.ic_启动器_前台)
.into(profile!!)
//image.setImageResource(retro1.profile_pic)
}
否则{
试一试{
瓦尔·乔布杰罗=
JSONObject(response.errorBody()!!.string())
Toast.makeText(
应用上下文,
jObjError.getString(“用户消息”),
吐司,长度
).show()
}捕获(e:例外){
Toast.makeText(applicationContext,e.message,Toast.LENGTH\u LONG.show())
Log.e(“errorr”,e.message)
}
}
}
})
profile?.setOnClickListener(View.OnClickListener{
val intent=intent()
intent.type=“image/*”
intent.action=intent.action\u获取内容
startActivityForResult(意图、图像)
})
editsubmit.setOnClickListener{
val first_name=firstname.text.toString().trim()
val last_name=lastname.text.toString().trim()
val email=emailregister.text.toString().trim()
val phone=phoneno.text.toString().trim()
val profile=“data:image/png;base64,”+convertToString()!!
val标记:字符串=
SharedPrefManager.getInstance(
应用程序上下文
).user.access_token.toString()
val first_name1=
create(MediaType.parse(“text/plain”),名字)
瓦尔姓1=
create(MediaType.parse(“text/plain”),姓氏)
val电子邮件1=
create(MediaType.parse(“text/plain”),电子邮件)
val dob1=
create(MediaType.parse(“text/plain”),edittext1.text.toString()
瓦尔电话1号=
create(MediaType.parse(“text/plain”),phone)
val profile_pic=RequestBody.create(
MediaType.parse(“文本/普通”),
轮廓
)
val intent=intent(这是HomeActivity::class.java)
intent.putExtra(“位图图像”,配置文件)
val-map:MutableMap=HashMap()
地图放置(“名字”,名字1);
地图放置(“姓氏”,姓氏1);
map.put(“email”,email1);
地图放置(“dob”,dob1);
地图放置(“电话号码”,电话号码1);
地图放置(“剖面图”,剖面图);
val requestFile:RequestBody=
create(MediaType.parse(“image/jpeg”),配置文件)
val body:MultipartBody.Part=
MultipartBody.Part.createFormData(“
class EditProfile:AppCompatActivity (){
private val IMAGE = 100
var bitmap: Bitmap? = null
var profile:ImageView?=null
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.editprofile)
    var mActionBarToolbar = findViewById<androidx.appcompat.widget.Toolbar>(R.id.toolbartable);
    setSupportActionBar(mActionBarToolbar);
    // add back arrow to toolbar
    if (getSupportActionBar() != null){
        getSupportActionBar()?.setDisplayHomeAsUpEnabled(true);
        getSupportActionBar()?.setDisplayShowHomeEnabled(true);
        getSupportActionBar()?.setHomeAsUpIndicator(R.drawable.ic_keyboard_arrow_left_black_24dp);
        getSupportActionBar()?.setDisplayShowTitleEnabled(false);

        //supportActionBar?.setTitle("Tables")
        //    getSupportActionBar()?.setTitle((Html.fromHtml("<font color=\"#FFFFFF\">" + getString(R.string.Myaccount) + "</font>")));

    }
    val myCalendar: Calendar = Calendar.getInstance()

    val edittext1 = findViewById(R.id.dob) as EditText
    val date =
        OnDateSetListener { view, year, monthOfYear, dayOfMonth -> // TODO Auto-generated method stub
            myCalendar.set(Calendar.YEAR, year)
            myCalendar.set(Calendar.MONTH, monthOfYear)
            myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth)
            val myFormat = "dd-MM-yyyy" //In which you need put here
            val sdf = SimpleDateFormat(myFormat, Locale.US)
            edittext1.setText(sdf.format(myCalendar.getTime()))      }

    edittext1.setOnClickListener(object : View.OnClickListener {
        override fun onClick(v: View?) {
            // TODO Auto-generated method stub
            DatePickerDialog(
                this@EditProfile, date, myCalendar
                    .get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
                myCalendar.get(Calendar.DAY_OF_MONTH)
            ).show()
        }
    })
   val edit= edittext1.text
     profile = findViewById<View>(R.id.profilepic) as ImageView


    val token :String =SharedPrefManager.getInstance(applicationContext).user.access_token.toString()
    RetrofitClient.instance.fetchUser(token)
        .enqueue(object : Callback<My_account_base_response> {
            override fun onFailure(call: Call<My_account_base_response>, t: Throwable) {

                Log.d("res", "" + t)


            }

            override fun onResponse(
                call: Call<My_account_base_response>,
                response: Response<My_account_base_response>
            ) {
                var res = response

                if (res.body()?.status==200) {
                    //  val retro: List<Myaccount_data> = response.body().getData()

                    val retro: Myaccount_data = res.body()!!.data
                    val retro1 : User_data =retro.user_data
                    Glide.with(applicationContext).load(retro1.profile_pic)
                        .diskCacheStrategy(DiskCacheStrategy.ALL)
                        .placeholder(R.drawable.ic_launcher_foreground)
                        .into(profile!!)
                    //image.setImageResource(retro1.profile_pic)
                }
                else{
                    try {
                        val jObjError =
                            JSONObject(response.errorBody()!!.string())
                        Toast.makeText(
                            applicationContext,
                         jObjError.getString("user_msg"),
                            Toast.LENGTH_LONG
                        ).show()
                    } catch (e: Exception) {
                        Toast.makeText(applicationContext, e.message, Toast.LENGTH_LONG).show()
                        Log.e("errorrr",e.message)
                    }
                }
            }
        })




    profile?.setOnClickListener(View.OnClickListener {

        val intent = Intent()
        intent.type = "image/*"
        intent.action = Intent.ACTION_GET_CONTENT
        startActivityForResult(intent, IMAGE)
    })
    editsubmit.setOnClickListener {

        val first_name = firstname.text.toString().trim()
        val last_name = lastname.text.toString().trim()

        val email = emailregister.text.toString().trim()
        val phone = phoneno.text.toString().trim()

        val profile ="data:image/png;base64,"+convertToString()!!
        val token: String =
            SharedPrefManager.getInstance(
                applicationContext
            ).user.access_token.toString()
        val first_name1 =
            RequestBody.create(MediaType.parse("text/plain"), first_name)
        val last_name1 =
            RequestBody.create(MediaType.parse("text/plain"), last_name)
        val email1 =
            RequestBody.create(MediaType.parse("text/plain"), email)
        val dob1 =
            RequestBody.create(MediaType.parse("text/plain"), edittext1.text.toString())
        val phone_no1 =
            RequestBody.create(MediaType.parse("text/plain"), phone)
        val profile_pic = RequestBody.create(
            MediaType.parse("text/plain"),
            profile
        )


        val intent = Intent(this, HomeActivity::class.java)
        intent.putExtra("BitmapImage", profile)
        val map: MutableMap<String, RequestBody> = HashMap()

        map.put("first_name", first_name1);
        map.put("last_name", last_name1);
        map.put("email", email1);
        map.put("dob", dob1);
        map.put("phone_no", phone_no1);
        map.put("profile_pic", profile_pic);
        val requestFile: RequestBody =
            RequestBody.create(MediaType.parse("image/jpeg"), profile)

        val body: MultipartBody.Part =
            MultipartBody.Part.createFormData("image", "image.jpg", requestFile)
        RetrofitClient.instance.useredit(token,map)
            .enqueue(object : Callback<LoginResponse> {
                override fun onFailure(call: Call<LoginResponse>, t: Throwable) {
                    Log.d("res", "" + t)
                }
                override fun onResponse(
                    call: Call<LoginResponse>,
                    response: Response<LoginResponse>
                ) {
                    var res = response
                    Log.d("response check ", "" + response.body()?.status.toString())
                    if (res.body()?.status==200) {
                        Toast.makeText(
                            applicationContext,
                            res.body()?.message,
                            Toast.LENGTH_LONG
                        ).show()
                        Log.d("kjsfgxhufb",response.body()?.status.toString())
                    }
                    else
                    {
                        try {
                            val jObjError =
                                JSONObject(response.errorBody()!!.string())
                            Toast.makeText(
                                applicationContext,
                                jObjError.getString("message")+jObjError.getString("user_msg"),
                                Toast.LENGTH_LONG
                            ).show()
                        } catch (e: Exception) {
                            Toast.makeText(applicationContext, e.message, Toast.LENGTH_LONG).show()
                            Log.e("errorrr",e.message)
                        }
                    }

                }
            })
    }
}
private fun convertToString(): String? {
      val byteArrayOutputStream = ByteArrayOutputStream()
    bitmap?.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream)
    bitmap?.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream)

    val imgByte: ByteArray = byteArrayOutputStream.toByteArray()

    return android.util.Base64.encodeToString(imgByte, android.util.Base64.NO_WRAP )
}

override fun onActivityResult(
    requestCode: Int,
    resultCode: Int,
    data: Intent?
) {
    super.onActivityResult(requestCode, resultCode, data)
    if (requestCode == IMAGE && resultCode == Activity.RESULT_OK && data != null) {
        val path: Uri? = data.data
        try {
            bitmap = MediaStore.Images.Media.getBitmap(contentResolver, path)
            profile?.setImageBitmap(bitmap)
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
    return when (item.itemId) {
        android.R.id.home -> {
            NavUtils.navigateUpFromSameTask(this)

            true
        }
        else -> super.onOptionsItemSelected(item)
    }
}
}
// start picker to get image for cropping and then use the image in cropping activity
CropImage.activity()
  .setGuidelines(CropImageView.Guidelines.ON)
  .start(this);