Преобразование из файла в растровое изображение в Android

Хорошо, я обновил свой вопрос. Это мое изображение для загрузки на сервер проекта. Все отлично работает без ошибок, но я продолжаю получать файлы размером 10, 12 или 16 байт. Но с правильным именем и типом.

            public class MainActivity extends AppCompatActivity implements View.OnClickListener {



private int PICK_IMAGE_REQUEST = 1;

private Button buttonChoose;
private Button buttonUpload;
String attachmentName = "bitmap";
File f;
private ImageView imageView;
private Bitmap bitmap;
private Bitmap bit;
ByteArrayBody bitmapBody;
ContentBody contentPart;
private Uri filePath;
private String stringPath;
byte[] bitmapdata;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
int SDK_INT = android.os.Build.VERSION.SDK_INT;
if (SDK_INT > 8) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
buttonChoose = (Button) findViewById(R.id.buttonChoose);
buttonUpload = (Button) findViewById(R.id.buttonUpload);

imageView = (ImageView) findViewById(R.id.imageView);

buttonChoose.setOnClickListener(this);
buttonUpload.setOnClickListener(this);
}
}




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);
}

@Override
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) {

filePath = data.getData();
Log.d(""+filePath,"PATHHH");
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
} catch (Exception e) {
e.printStackTrace();
}
}
}

public void getStringImage(){
try {

stringPath = getRealPathFromUri(getApplicationContext(), filePath);
f = new File(stringPath);
Log.d("FAJLEE" + f, "2");
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100 /*ignored for png*/ , bos);
byte[] bitmapdata = bos.toByteArray();
FileOutputStream fos = new FileOutputStream(f);
fos.write(bitmapdata);
fos.flush();
fos.close();

} catch (Exception e) {
e.printStackTrace();
Log.e(getClass().getSimpleName(), "Error writing bitmap", e);
}
}





public static String getRealPathFromUri(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = { MediaStore.Images.Media.DATA };
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}



public void uploadImage(){
try {
Log.d("Stefna ", "ajdbarovde");
DefaultHttpClient httpclient = new DefaultHttpClient();
InputStream responseStream = null;
String responseString = "";
try {
HttpPost httppost = new HttpPost("http://studentskioglas.com/aplikacija/upload.php");

BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bit = BitmapFactory.decodeFile(f.getAbsolutePath(), bmOptions);
//   bit = BitmapFactory.decodeByteArray(bitmapdata, 0, bitmapdata.length, bmOptions);
Log.d("Usao u fajlee","");

HttpEntity reqEntity = MultipartEntityBuilder.create()
.addBinaryBody("bitmap", bitmapdata, ContentType.create("image/jpg"), f.getName())
.build();
Log.d("Stefan ", f+"FAJLEEE");

httppost.setEntity(reqEntity);

System.out.println("executing request " + httppost.getRequestLine());
HttpResponse response = httpclient.execute(httppost);Log.d("Stefan", "ispod");
try {
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
Log.d("Response content l: " + resEntity.getContentLength(), "");

responseStream = resEntity.getContent();
if (responseStream != null) {
BufferedReader br = new BufferedReader(new InputStreamReader(responseStream));
String responseLine = br.readLine();
String tempResponseString = "";
while (responseLine != null) {
tempResponseString = tempResponseString + responseLine + System.getProperty("line.separator");
responseLine = br.readLine();
}
br.close();
if (tempResponseString.length() > 0) {
responseString = tempResponseString;
Log.d(""+responseString,"");
}
}

}

} finally {
response = null;
}
} finally {
httpclient = null;
}
} catch (Exception e) {
e.printStackTrace();
} }

@Override
public void onClick(View v) {
if (v == buttonChoose) {
showFileChooser();
}
if(v == buttonUpload){
getStringImage();
uploadImage();
imageView.setImageBitmap(bit);
}

Мои пути выглядят хорошо. Сначала я подумал, что проблема заключается в преобразовании растровых изображений в файлы, но это не так. Поэтому я попытался преобразовать его обратно, чтобы увидеть, есть ли какая-то неисправность, я удалил AsyncTask, и теперь я могу видеть изображение, преобразованное обратно из файла, поэтому я знаю, что отправляю хороший файл с правильным размером и всеми параметрами. Но на сервере у меня есть небольшие файлы, которые при загрузке я не вижу. Это мой PHP скрипт на стороне сервера.

<?php

$target_path = "images/";

$target_path = $target_path . basename( $_FILES['bitmap']['name']);

if(file_put_contents($target_path, $_FILES['bitmap']['name'])) {


echo "The file ".  basename( $_FILES['bitmap']['name']).

" has been uploaded";

} else{
echo "There was an error uploading the file, please try again!";
} ?>

Просто для обновления я нашел ответ. Ошибка была в file_put_contents, это должен быть move_uploaded_file, но с $ _FILE [‘your tag’] [‘tmp_name’]. Не смущайтесь, если измените его на $ _FILE [‘your tag’] [‘name’], потому что [‘tmp_name’] — это имя вашего файла в данный момент, и это имя, которое видит сервер.

0

Решение

Я обычно использую вспомогательные методы ниже, которые работают довольно хорошо. Дай им попробовать.

public static Bitmap convertBLOB2Bitmap(byte[] blob) {
Options options = new BitmapFactory.Options();
Bitmap tmp = BitmapFactory.decodeByteArray(blob, 0, blob.length, options);
return tmp;
}


public static byte[] convertBitmap2BLOB(Bitmap bitmap) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0 /* ignored for PNG */, bos);
return bos.toByteArray();
}
1

Другие решения

используйте этот код

File imgFile = new  File(selectedImageUrl);
if(imgFile.exists()){
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
}
1