将数据库中的图像作为字符串接收并将其转换为位图并设置为imageView

时间:2016-07-17 08:08:04

标签: android bitmap base64 android-imageview

我有数据库保存在字符串格式中,然后我收到了字符串到android。现在我想将字符串转换为base64并将其设置为imageView。但我在将位图设置为imageView时遇到了麻烦。

这是我的代码:

   /**
 * @param encodedString
 * @return bitmap (from given string)
 */
public Bitmap StringToBitMap(String encodedString){
    try {
        byte [] encodeByte=Base64.decode(encodedString,Base64.DEFAULT);
        Bitmap bitmap=BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
        ImageView imageView=(ImageView)findViewById(R.id.ivProfilePic);
        assert imageView != null;
        imageView.setImageBitmap(bitmap);
        return bitmap;
    } catch(Exception e) {
        e.getMessage();
        return null;
    }
}

然后我使用具有精确字符串'image'的参数调用此函数。

    StringToBitMap(image);

My Mian Android Code:

  public class Profile extends AppCompatActivity {

public String image;
public ImageView imageVieww;
public Bitmap bitmap;
public int PICK_IMAGE_REQUEST = 1;

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


    ProfilePicRetrive();
    StringToBitMap(image);

    imageVieww=(ImageView)findViewById(R.id.ivProfilePic);



    TextView tvUploadProfilePic = (TextView)findViewById(R.id.tvUploadProfilePic);

    if (imageVieww != null) {
        imageVieww.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showFileChooser();
            }
        });
    }

    assert tvUploadProfilePic != null;
    tvUploadProfilePic.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String image = getStringImage(bitmap);
            String user_id=UserDetails.user_id;
            Response.Listener<String> responseListener = new Response.Listener<String>() {

                final ProgressDialog pd = ProgressDialog.show(Profile.this,"", "Registering your Account", true);

                @Override
                public void onResponse(String response) {
                    try {
                        JSONObject jsonResponse = new JSONObject(response);
                        boolean success = jsonResponse.getBoolean("success");
                        if (success) {
                            pd.dismiss();

                        } else {
                            AlertDialog.Builder builder = new AlertDialog.Builder(Profile.this);
                            builder.setMessage("Register Failed")
                                    .setNegativeButton("Retry", null)
                                    .create()
                                    .show();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            };

            ProfileRequest profileRequest = new ProfileRequest(image, user_id, responseListener);
            RequestQueue queue = Volley.newRequestQueue(Profile.this);
            queue.add(profileRequest);
        }
    });
}
private void ProfilePicRetrive () {
    class GetEmployee extends AsyncTask<Void, Void, String> {
        ProgressDialog loading;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            loading = ProgressDialog.show(Profile.this, "Fetching...", "Wait...", false, false);
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            loading.dismiss();
            showEmployee(s);
        }

        @Override
        protected String doInBackground(Void... params) {
            RequestHandler rh = new RequestHandler();
            String s = rh.sendGetRequestParam(Config.URL_GET_EMP, UserDetails.user_id);
            return s;
        }
    }
    GetEmployee ge = new GetEmployee();
    ge.execute();
}



private void showEmployee(String json) {
    try {
        JSONObject jsonObject = new JSONObject(json);
        JSONArray result = jsonObject.getJSONArray(Config.TAG_JSON_ARRAY);
        JSONObject c = result.getJSONObject(0);
        image = c.getString(Config.TAG_IMAGE);
        Toast.makeText(getApplicationContext(),image,Toast.LENGTH_LONG).show();

    } catch (JSONException e) {
        e.printStackTrace();
    }
}


/**
 * @param encodedString
 * @return bitmap (from given string)
 */
public Bitmap StringToBitMap(String encodedString){
    try {
        byte [] encodeByte=Base64.decode(encodedString,Base64.DEFAULT);
        Bitmap bitmap=BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
        ImageView test=(ImageView)findViewById(R.id.testt);
        assert test != null;
        test.setImageBitmap(Bitmap.createScaledBitmap(bitmap, 120, 120, false));
        return bitmap;
    } catch(Exception e) {
        e.getMessage();
        return null;
    }
}
private void showFileChooser() {
    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
        Uri filePath = data.getData();
        try {
            //Getting the Bitmap from Gallery
            bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
            //Setting the Bitmap to ImageView
            imageVieww.setImageBitmap(bitmap);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

public String getStringImage(Bitmap bmp){
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bmp.compress(Bitmap.CompressFormat.JPEG,30,baos);
    byte[] imageBytes = baos.toByteArray();
    return Base64.encodeToString(imageBytes, Base64.DEFAULT);
}
}

我的Xml代码(用于imageView和上传按钮)

   <RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin">

    <ImageView
        android:layout_width="250dp"
        android:layout_height="100dp"
        android:id="@+id/ivProfilePic"
        android:padding="10dp"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Upload"
        android:id="@+id/tvUploadProfilePic"
        android:layout_marginRight="40dp"
        android:layout_marginEnd="40dp"
        android:layout_centerVertical="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />
</RelativeLayout>

这是我的错误,它是蓝色的:

   07-17 13:54:29.093 9304-9304/com.cuboid.cuboid I/Choreographer: Skipped                                                     36 frames!  The application may be doing too much work on its main thread.
    07-17 13:54:43.436 9304-9540/com.cuboid.cuboid W/System.err:   java.net.SocketTimeoutException: failed to connect to   allwaysready.16mb.com/31.170.164.89 (port 80) after 15000ms
    07-17 13:54:43.436 9304-9540/com.cuboid.cuboid W/System.err:     at    libcore.io.IoBridge.connectErrno(IoBridge.java:169)
   07-17 13:54:43.436 9304-9540/com.cuboid.cuboid W/System.err:      at   libcore.io.IoBridge.connect(IoBridge.java:122)
   07-17 13:54:43.436 9304-9540/com.cuboid.cuboid W/System.err:     at   java.net.PlainSocketImpl.connect(PlainSocketImpl.java:183)
   07-17 13:54:43.436 9304-9540/com.cuboid.cuboid W/System.err:     at  java.net.PlainSocketImpl.connect(PlainSocketImpl.java:456)
   07-17 13:54:43.436 9304-9540/com.cuboid.cuboid W/System.err:     at java.net.Socket.connect(Socket.java:882)
   07-17 13:54:43.437 9304-9540/com.cuboid.cuboid W/System.err:     at  com.android.okhttp.internal.Platform.connectSocket(Platform.java:174)
   07-17 13:54:43.437 9304-9540/com.cuboid.cuboid W/System.err:     at com.android.okhttp.Connection.connect(Connection.java:152)
   07-17 13:54:43.437 9304-9540/com.cuboid.cuboid W/System.err:     at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:276)
   07-17 13:54:43.437 9304-9540/com.cuboid.cuboid W/System.err:     at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:211)
   07-17 13:54:43.437 9304-9540/com.cuboid.cuboid W/System.err:     at     com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnection  Impl.java:382)
   07-17 13:54:43.437 9304-9540/com.cuboid.cuboid W/System.err:     at com.android.okhttp.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:106)
   07-17 13:54:43.437 9304-9540/com.cuboid.cuboid W/System.err:     at com.android.okhttp.internal.http.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:217)
   07-17 13:54:43.437 9304-9540/com.cuboid.cuboid W/System.err:     at com.cuboid.cuboid.RequestHandler.sendPostRequest(RequestHandler.java:52)
   07-17 13:54:43.437 9304-9540/com.cuboid.cuboid W/System.err:     at com.cuboid.cuboid.PostJobs$1AddJobs.doInBackground(PostJobs.java:129)
   07-17 13:54:43.437 9304-9540/com.cuboid.cuboid W/System.err:     at com.cuboid.cuboid.PostJobs$1AddJobs.doInBackground(PostJobs.java:92)
   07-17 13:54:43.437 9304-9540/com.cuboid.cuboid W/System.err:     at android.os.AsyncTask$2.call(AsyncTask.java:292)
   07-17 13:54:43.437 9304-9540/com.cuboid.cuboid W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
   07-17 13:54:43.437 9304-9540/com.cuboid.cuboid W/System.err:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
   07-17 13:54:43.437 9304-9540/com.cuboid.cuboid W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
    07-17 13:54:43.437 9304-9540/com.cuboid.cuboid W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
   07-17 13:54:43.437 9304-9540/com.cuboid.cuboid W/System.err:     at java.lang.Thread.run(Thread.java:818)
   07-17 13:55:05.178 9304-9312/com.cuboid.cuboid I/art: Debugger is no longer active
   07-17 13:55:29.775 9304-9312/com.cuboid.cuboid W/art: Suspending all threads took: 13.073ms

0 个答案:

没有答案