Преобразование из файла в растровое изображение в 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'] – это имя вашего файла в этот конкретный момент, и это имя, которое видит сервер.

Related of "Преобразование из файла в растровое изображение в android"