编码字节结果非常短

时间:2017-08-31 18:11:49

标签: c#

我创建了一个位图截图:

Bitmap screenshot = TakeScreenshot();
byte[] bytes = ImageToByte(screenshot, System.Drawing.Imaging.ImageFormat.Bmp);

现在我尝试编码:

string imageData = Encoding.UTF8.GetString(bytes);

但是,如果我在富文本框中输出此字符串,那么我得到的结果是:

BM6�~

即使imageData的长度为 8277082

发生了什么事?

功能

public static byte[] ImageToByte(Image img, System.Drawing.Imaging.ImageFormat format)
{
    using (var stream = new System.IO.MemoryStream()) {
        img.Save(stream, format);
        return stream.ToArray();
    }
}

private Bitmap TakeScreenshot()
{
    //Create a new bitmap.
    var bmpScreenshot = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
                                   Screen.PrimaryScreen.Bounds.Height,
                                   System.Drawing.Imaging.PixelFormat.Format32bppArgb);

    // Create a graphics object from the bitmap. (geht auch ohne das using gedöns, aber mit using ist es besser)
    using (var gfxScreenshot = Graphics.FromImage(bmpScreenshot)) {
        // Take the screenshot from the upper left corner to the right bottom corner.
        gfxScreenshot.CopyFromScreen(Screen.PrimaryScreen.Bounds.X,
                                Screen.PrimaryScreen.Bounds.Y,
                                0,
                                0,
                                Screen.PrimaryScreen.Bounds.Size,
                                CopyPixelOperation.SourceCopy);
    }

    return bmpScreenshot;
}

4 个答案:

答案 0 :(得分:7)

您不能在不实际代表字符串的内容上使用Encoding.UTF8.GetString。编码失败(如您所见),您需要使用可以处理任意字节的编码,如Base 64编码

string imageData = Convert.ToBase64String(bytes);

在服务器上获取你使用的字节

byte[] imageDataAsBytes = Convert.FromBase64String(imageDataAsString);

有一点需要注意,使用base 64编码将导致字符串占用原始大小的4/3(以字节为单位)。如果可能,请尝试调查是否可以将原始byte []发送到服务器而不是先将其编码为字符串,这样可以减少传输的数据。

答案 1 :(得分:6)

您试图在字符串中表示二进制数据,但字符串不能表示每个二进制数据。

如果你想要一个字符串,那么你需要使用某种形式的编码作为最常见的Base64。

更改

string imageData = Encoding.UTF8.GetString(bytes);

string imageData = Convert.ToBase64String(bytes);

请记住,要恢复原始二进制数据,您必须对其进行解码:

byte[] data = Convert.FromBase64String(imageData);

答案 2 :(得分:5)

将二进制数据编码为字符串是错误的,而必须使用Convert.ToBase64String()来获取可以转换回字节的文本表示。

答案 3 :(得分:4)

edu.abc.company.orm.dao

...仅在package edu.abc.company.orm.dao.impl; import java.util.List; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.support.ClassPathXmlApplicationContext; import edu.abc.company.orm.EmployeeMetaData; import edu.abc.company.orm.dao.EmployeeMetaDataDao; import edu.abc.company.util.Util; public class EmployeeMetaDataDaoImpl implements EmployeeMetaDataDao { public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } @SuppressWarnings("unchecked") public List<EmployeeMetaData> list() { logger.debug("Starting EmployeeMetaDataDaoImpl.list() ....."); Session session = null; List<EmployeeMetaData> EmployeeMetaData = null; try { session = this.sessionFactory.openSession(); EmployeeMetaData = session.createQuery("FROM EmployeeMetaData").list(); } catch(Exception ex) { ex.printStackTrace(); } finally { session.close(); } logger.debug("Completed EmployeeMetaDataDaoImpl.list() ....."); return EmployeeMetaData; } public List<EmployeeMetaData> findByEmpAndInfoId(int employee_id, int information_id) { List<EmployeeMetaData> EmployeeMetaData = null; Session session = null; try { session = this.sessionFactory.openSession(); EmployeeMetaData = session.createQuery("FROM EmployeeMetaData WHERE information_id = '" + information_id + "'" + " AND company_id = '" + employee_id + "'").list(); } catch(Exception ex) { ex.printStackTrace(); } finally { session.close(); } return EmployeeMetaData; } // Main method goes here public static void main(String[] args) { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml"); try{ EmployeeMetaDataDao rpcDao = (EmployeeMetaDataDao)context.getBean("EmployeeMetaDataDao"); List<EmployeeMetaData> EmployeeMetaData = rpcDao.list(); if ((EmployeeMetaData != null) && EmployeeMetaData.size() > 0) { for (int i=0;i<EmployeeMetaData.size();i++) { EmployeeMetaData re = EmployeeMetaData.get(i); } } context.close(); } catch(Throwable th) { th.printStackTrace(); } finally { context.close(); } } private SessionFactory sessionFactory; private static final Logger logger = LoggerFactory.getLogger(EmployeeMetaDataDaoImpl.class); } 包含UTF8编码的字符串时有效。否则你会得到垃圾。

如果要将图像存储为字符串,请考虑在BASE64中对其进行编码:

string imageData = Encoding.UTF8.GetString(bytes);